<?php
class wapi_controller extends general_controller{
    public function __construct(){
        parent::__construct();
        $this->_weixin = array(
            'appid' =>'wxeefd45e32d9364dc',
            'secret'=>'005da7dac6d10484287f4ebc9967ad0a',
            'mchid' => '1482407062',
            'key' => '005da7dac6d10484287f4ebc9967ad0a',
            'notify_url'=>'https://read.kuajiewl.com/wapi/wxpay_notify.html',
            'vip_notify_url'=>'https://read.kuajiewl.com/wapi/wxpay_notify_vip.html',
            'vip_notify_url'=>'https://read.kuajiewl.com/wapi/wxpay_notify_guwen.html',
            'postage_notify_url'=>'https://read.kuajiewl.com/wapi/wxpay_notify_postage.html',
            'income_type' => ['直推奖','收藏','服务奖','分享产品返利（一级返利）','间推奖'],
            'prize' => ['金卡VIP直推补贴','金卡VIP收藏','金卡VIP服务补贴','尊贵VIP直推补贴','尊贵VIP收藏补贴','尊贵VIP服务补贴','二级补贴'],

        );
        $this->_wx_template = 'hDuWaRojW0-5vKgDMenMjo8UUzEfpl7sEyyBYcamdP0';
        $this->_key_user = 'user_';
        $this->_key_user_cart = 'cart_';
        $this->_cache_year = 31536000;
        $this->_postage_price = 0.01;
        $this->_order_status = array('交易取消','等待付款','等待发货','等待签收','交易完成');
        $this->_vip_price = ['vip1' => 0.01, 'vip2' => 0.01];
    }

    public function action_index(){
        $vcache = vcache::instance();

        $data['ad'] = $vcache->adv_model('adv_index', array(array('position_id' => 1), 5), $GLOBALS['cfg']['data_cache_lifetime']);
        $data['gonggao'] = $vcache->help_model('help_index', array(['id' => 4]), $GLOBALS['cfg']['data_cache_lifetime']);
        $data['class'] = $vcache->goods_cate_model('cate_index', array(20), $GLOBALS['cfg']['data_cache_lifetime']);
        $recommend = $vcache->goods_model('find_goods_newarrival', array(array('newarrival' => 1), 100), $GLOBALS['cfg']['data_cache_lifetime']);
        $data['recommend'] = empty($recommend) ? [] :array_slice($recommend,0,10);
        $data['king'] = $vcache->goods_model('find_goods_index', array(array('cate_id' => 18,'recommend' => 1), 2), $GLOBALS['cfg']['data_cache_lifetime']);
        //$data['zun'] = $vcache->goods_model('find_goods', array(array('zun' => 1,'recommend' => 1), 1), $GLOBALS['cfg']['data_cache_lifetime']);


        $lat = $vcache->setting_model('get_config_index', null, $GLOBALS['cfg']['data_cache_lifetime']);
        $vip_setting = json_decode($lat['vip_settings'], true);
        $data['lat'] = ['site_name' => $lat['site_name'], 'king_price' => $vip_setting['king_price']];

        jsonEcho($data);

        jsonEcho(['ret' => 0, 'data' => $data]);
    }
    //回调邀请人
    public function action_update_invite(){
        $openid = request('openid', '');
        if ($openid == '') {
            jsonEcho(['ret' => 10]);
        }

        $user_model = new user_model();
        $user = $user_model->find(array('openid' => $openid), null, 'user_id,invite,openid');
        if(!$user || $user['invite'] != 0){
            jsonEcho(['ret' => 11]);
        }

        $invite = (int)request('invite', 0);
        if($user['user_id'] == $invite){
            jsonEcho(['ret' => 12]);
        }
        if($invite > 0){
            $res = $user_model->update(array('openid' => $openid), array('invite' => $invite));
            if($res){
                jsonEcho(['ret' => 0]);
            }
        }
        jsonEcho(['ret' => 13]);
    }

    public function action_goods_list(){
        $page = (int)request('page', 0);
        if($page < 2){
            jsonEcho(array('ret' => 1));
        }
        $vcache = vcache::instance();
        $recommend = $vcache->goods_model('find_goods', array(array('recommend' => 1), 100), $GLOBALS['cfg']['data_cache_lifetime']);
        $start = ($page - 1) * 10;
        $data['goods_list'] = array_slice($recommend, $start, 10);
        jsonEcho($data);
    }
    public function action_category(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];


        $id = (int)request('cate_id', 0);
        $vip = $uinfo['data']['vip'];
        $data['pay'] = 0;
        if($vip < 1){
            $data['pay'] = 1;
        }

        $vcache = vcache::instance();
        $data['cate_list'] = $vcache->goods_cate_model('cate_index', array(20), $GLOBALS['cfg']['data_cache_lifetime']);
        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        $data['vip_settings'] = json_decode($rs['vip_settings'], true);

        if(!isset($_POST['page'])){
            $page = 0;
        }else{
            $page = (int)request('page', 0);
        }
        $start = $page * 10;

        $order_model = new order_model();
        $order = $order_model->query("SELECT b.goods_id FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order AS a LEFT JOIN {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order_goods AS b ON a.order_id=b.order_id WHERE a.order_status=2");

        $ordered = [];
        if(!empty($order)){
            foreach($order as $o){
                $ordered[] = $o['goods_id'];
            }
        }
        if($id == 0){
            //$data['goods_list'] = $vcache->goods_model('bestseller', array(100), $GLOBALS['cfg']['data_cache_lifetime']);
            $goods_model = new goods_model();
            $fields = 'goods_id, goods_name, now_price,rake_back, goods_image,sell,king,zun';
            //$sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods WHERE king='1' OR zun='1' AND status='1' ORDER BY goods_id DESC limit $start, 10";
            $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods WHERE recommend='0' AND status='1' ORDER BY goods_id DESC limit $start, 10";
            //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            $goods_model = new goods_model();
            $data['goods_list'] = $goods_model->query($sql);


        }else{
            $cate_model = new goods_cate_model();
            if($cateinfo = $cate_model->find(array('cate_id' => $id))){
                $conditions = array(
                    'cate' => $id,
                    'page' => (int)request('page', 1),
                );

                $fields = 'goods_id, goods_name, now_price, rake_back,goods_image,sell,king,zun';
                $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods WHERE cate_id='{$id}' AND status='1' ORDER BY goods_id DESC limit $start, 10";
                //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                $goods_model = new goods_model();
                $data['goods_list'] = $goods_model->query($sql);
                //$data['goods_list'] = $goods_model->find_goods($conditions, array(request('page', 1), $GLOBALS['cfg']['cate_goods_per_num']));
            }
        }
        if($vip < 1){
            foreach($data['goods_list'] as $k => $v){
                if(in_array($v['goods_id'], $ordered)){
                    $data['goods_list'][$k]['payed'] = 1;
                }else{
                    $data['goods_list'][$k]['payed'] = 0;
                }
            }
        }
        jsonEcho(array('ret' => 0, 'data' => $data));
    }
    /**
     * 收藏商品
     */
    public function action_product_fav(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $favor_model = new user_favorite_model();
        if($favor_model->add($user_id, (int)request('goods_id', 0))) {
            jsonEcho(array('ret' => 0));
        }else {
            jsonEcho(array('ret' => 1, 'err' => '已收藏'));
        }
    }
    public function action_favlist(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $fav_model = new user_favorite_model();
        $list = $fav_model->get_user_favorites($user_id, array(request('page', 1), request('pernum', 10)));
        if($list) {
            $res = array('ret' => 0, 'list' => $list, 'paging' => $fav_model->page);
        }else {
            $res = array('ret' => 1);
        }
        jsonEcho($res);
    }

    public function action_favdelete(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $id = request('id');
        if($id) {
            $fav_model = new user_favorite_model();
            if(is_array($id)) {
                foreach($id as $v) $fav_model->delete(array('goods_id' => (int)$v, 'user_id' => $user_id));
            } else {
                $fav_model->delete(array('goods_id' => (int)$id, 'user_id' => $user_id));
            }
            jsonEcho(array('ret' => 0));
        }else {
            jsonEcho(array('ret' => 1, 'msg' => '参数非法'));
        }
    }

    /**
     * 商品详情
     */
    public function action_product_index(){

        if(!isset($_POST['openid']) && !isset($_POST['seesionid'])){
            jsonEcho(array('ret' => 1, 'msg' => '你还不是VIP'));
        }
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($_REQUEST, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);



        $id = (int)request('id', 0);
        $condition = array('goods_id' => $id);

        $goods_model = new goods_model();
        if($goods = $goods_model->find($condition)){

            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($goods_model->dump_sql(), true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            if($goods['cate_id'] != 18){
                $order_model = new order_model();
                $order = $order_model->query("SELECT b.goods_id FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order AS a LEFT JOIN {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order_goods AS b ON a.order_id=b.order_id WHERE a.order_status=2 AND b.goods_id='{$id}'");

                if($uinfo['data']['vip'] < 1 && empty($order)){
                    jsonEcho(array('ret' => 2, 'msg' => '请付费阅读'));
                }
            }

            $goods_model->incr($condition, 'view');

            $cate_model = new goods_cate_model();
            $breadcrumbs = $cate_model->breadcrumbs($goods['cate_id']);
            $data['breadcrumbs'] = isset($breadcrumbs[0]) ? $breadcrumbs[0] : [];
            //商品信息
            unset($goods['goods_content2']);
            $data['goods'] = $goods;
            //商品相册
            $album_model = new goods_album_model();
            $data['album_list'] = $album_model->find_all($condition);
            //保存浏览历史
            //$goods_model->set_history($id);
            jsonEcho(array('ret' => 0, 'data'=> $data));
        } else{
            jsonEcho(array('ret' => 10, 'err'=>'商品不存在'));
        }
    }
    /**
     * 未付费详情
     */
    public function action_product_index2(){

        if(isset($_POST['openid']) && isset($_POST['seesionid'])){
            $openid = trim($_POST['openid']);
            $sessionId = trim($_POST['seesionid']);
            $uinfo = $this->wechat_is_login($openid, $sessionId);
            if($uinfo['ret'] > 0){
                jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
            }
            $user_id = $uinfo['data']['user_id'];
        }


        $id = (int)request('id', 0);
        $condition = array('goods_id' => $id);


        $goods_model = new goods_model();
        if($goods = $goods_model->find($condition)){
            $goods_model->incr($condition, 'view');

            $cate_model = new goods_cate_model();
            $breadcrumbs = $cate_model->breadcrumbs($goods['cate_id']);
            $data['breadcrumbs'] = isset($breadcrumbs[0]) ? $breadcrumbs[0] : [];
            //商品信息
            unset($goods['goods_content']);
            $data['goods'] = $goods;
            //商品相册
            $album_model = new goods_album_model();
            $data['album_list'] = $album_model->find_all($condition);
            //保存浏览历史
            //$goods_model->set_history($id);
            jsonEcho(array('ret' => 0, 'data'=> $data));
        } else{
            jsonEcho(array('ret' => 10, 'err'=>'商品不存在'));
        }
    }
    /**
     * 获取购物车
     */
    public function action_cart_index(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        if (!$user_id) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        $data = is_array($cart_info) ? array_values($cart_info) : array();
        jsonEcho(array('status' => 0,'data' => $data));
    }
    /**
     * 操作购物车
     */
    public function action_up_cart(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $goods_id = (int)($_POST['cart_id']);
        $num = (int)($_POST['num']);
        if (!$user_id || !$goods_id || ! $num) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        if(isset($cart_info[$goods_id])){
            $cart_info[$goods_id]['num'] = $num;
        }
        $vcache->set($key, $cart_info, $this->_cache_year);
        jsonEcho(array('status' => 0,'data' => array_values($cart_info)));
    }
    /**
     * 删除购物车
     */
    public function action_cart_delete(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $goods_id = (int)($_POST['cart_id']);
        if (!$user_id || !$goods_id) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        if(isset($cart_info[$goods_id])){
            unset($cart_info[$goods_id]);
        }
        $vcache->set($key, $cart_info, $this->_cache_year);
        jsonEcho(array('status' => 0,'data' => array_values($cart_info)));
    }
    /**
     * 购物车结算
     */
    public function action_payment_cart(){
        //cart_id:3,2, uid:1
        //$_POST['cart_id'] = '3,2,';
        //$_POST['user_id'] = 1;
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $goods_id = trim($_POST['cart_id']);
        if (!$user_id || !$goods_id) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        if(empty($cart_info)){
            jsonEcho(array('status' => 9,'err'=>'数据非法'));
        }
        $goods = explode(',', $goods_id);
        if(empty($goods)){
            jsonEcho(array('status' => 8,'err'=>'数据非法'));
        }

        $arr = array('total' => 0);

        $lat = $vcache->setting_model('get_config', null, $GLOBALS['cfg']['data_cache_lifetime']);
        $arr['business'] = json_decode($lat['business'], true);
        //获取商品信息
        foreach($goods as $g){
            $condition = array('goods_id' => $g);
            $goods_model = new goods_model();
            if($goods_info = $goods_model->find($condition)){
                $arr['total'] += $cart_info[$g]['num'] * $goods_info['now_price'];
            }
        }
        $arr['peisongfei'] = 0;
        if($arr['business']['business'] == 2 && $arr['total'] < $arr['business']['mianyou']){
            $arr['total'] = $arr['total'] + $arr['business']['peisongfei'];
            $arr['peisongfei'] = $arr['business']['peisongfei'];
        }

        //获取收货地址
        $consignee_model = new user_consignee_model();
        $arr['consignee_list'] = $consignee_model->get_user_consignee_list($user_id);
        if ($arr['consignee_list'] == null) {
            $arr['addemt'] = 0;
        }else{
            foreach($arr['consignee_list'] as $v){
                if($v['is_default']){
                    $arr['addemt'] = 0;
                    $arr['consignee_list'] = $v;
                    break;
                }else{
                    $arr['addemt'] = 1;
                }
            }
        }

        //获取优惠券
        $user_voucher_model = new user_voucher_model();
        $vinfo = $user_voucher_model->query("SELECT vid FROM {$user_voucher_model->table_name} WHERE user_id='{$user_id}' AND isused='0'");

        $arr['vou'] = [];
        if(!empty($vinfo)){
            $in = '';
            foreach($vinfo as $u){
                $in .= $u['vid'] . ',';
            }
            $in = substr($in, 0, -1);
            $voucher_model = new voucher_model();
            $today = strtotime('today');
            $results = $voucher_model->query("SELECT * FROM {$voucher_model->table_name} WHERE id in($in) AND end >= {$today}");
            if(!empty($results)) {
                foreach ($results as $ko => $vo) {
                    if ($vo['goods_use'] != 0) {
                        $garr = explode(',', $vo['goods_use']);
                        foreach($goods as $good_id){
                            if(in_array($good_id, $garr) && $arr['total'] >= $vo['greater_than']){
                                echo $arr['total'] .'+++'.$vo['greater_than'];
                                $arr['vou'][] = $vo;
                                break;
                            }
                        }
                    }else{
                        $arr['vou'][] = $vo;
                    }
                }
            }
        }

        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        $arr['cart'] = array();
        foreach($goods as $id){
            if(isset($cart_info[$id])){
                $arr['cart'][] = $cart_info[$id];
            }
        }

        jsonEcho(array('status' => 0,'data' => $arr));
    }
    /**
     * 支付
     */
    public function action_payment(){
        /**
         * seesionid:xr2V+7YcJ+z6WRQVse6y0Q==
        openid:o2S1c5X8AxIqgQo3Ita5s4w5_VP4
        cart_id:3,
        type:weixin
        aid:11
        remark:
        price:23
        vid:0
         */
        //$_POST['user_id'] = 1;$_POST['cart_id'] = '3,2,';$_POST['aid'] = 2;
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $paytype = trim($_POST['paytype']);
        if($paytype == 'company'){
            $payment_method = 1;
            $order_status = 2;
        }elseif($paytype == 'weixin'){
            $payment_method = 0;
            $order_status = 1;
        }else{
            jsonEcho(array('ret' => 55, 'msg'=>'不支持的购买方式'));
        }

        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($_REQUEST, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $vid = (int)request('vid', 0);
        $invite = (int)request('invite', 0);
        $goods_id = trim($_POST['cart_id']);
        //设置邀请人
        if($invite > 0){
            //设置邀请人
            $user_nodel = new user_model();
            $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user SET invite='{$invite}' WHERE user_id='{$user_id}' AND invite='0'";
            $user_nodel->query($sql);
        }

        //检查收件人信息
        /**$csn_id = (int)$_POST['aid'];
        $consignee_model = new user_consignee_model();
        if(!$consignee = $consignee_model->find(array('id' => $csn_id, 'user_id' => $user_id))){
            jsonEcho(array('ret' => 6, 'msg' => '无法获取收件人地址信息'));
        }**/
        /**$setting_model = new setting_model();
        $rs = $setting_model->get_config();
        $peisong = json_decode($rs['peisong_address'], true);
        $dist = json_decode($peisong['detail_info']['dist']);
        if(!in_array($consignee['borough'], $dist)){
            jsonEcho(array('ret' => 6, 'err' => '地址不在配送范围'));
        }**/

        //检查购物车信息
        $key = $this->_key_user_cart . $user_id;
        $vcache = vcache::instance();
        $cart_info = $vcache->get($key);
        $goods = explode(',', $goods_id);
        if(empty($cart_info) || empty($goods)){
            jsonEcho(array('status' => 8,'msg'=>'数据非法'));
        }
        $total = 0;
        $in = '';
        foreach($goods as $g){
            if(isset($cart_info[$g])){
                $total += $cart_info[$g]['num'] * $cart_info[$g]['now_price'];
                $goods_list[] = array('goods_id' => $cart_info[$g]['goods_id'], 'goods_name' => $cart_info[$g]['goods_name'], 'goods_image' => $cart_info[$g]['goods_image'], 'now_price' => $cart_info[$g]['now_price'], 'qty' => $cart_info[$g]['num']);
                $in .= $cart_info[$g]['goods_id'] . ',';
            }
        }
        if($vid > 0){
            //获取优惠券
            $user_voucher_model = new user_voucher_model();
            $uinfo = $user_voucher_model->query("SELECT vid FROM {$user_voucher_model->table_name} WHERE vid='{$vid}' AND user_id='{$user_id}' AND isused='0'");

            if(!empty($uinfo)){
                $use_vid = $uinfo[0]['vid'];
                $voucher_model = new voucher_model();
                $today = strtotime('today');
                $results = $voucher_model->query("SELECT * FROM {$voucher_model->table_name} WHERE id='{$use_vid}' AND end >= {$today}");
                if(!empty($results)) {
                        if ($results[0]['goods_use'] != 0) {
                            $garr = explode(',', $results[0]['goods_use']);
                            foreach($goods as $good_id){
                                if(in_array($good_id, $garr)){
                                    $total = $total - $results[0]['amount'];
                                }
                            }
                        }else{
                            if($total > $results[0]['greater_than']){
                                $total = $total - $results[0]['amount'];
                            }
                        }
                }
            }
        }
        $lat = $vcache->setting_model('get_config', null, $GLOBALS['cfg']['data_cache_lifetime']);
        $business = json_decode($lat['business'], true);
        $shipping_amount = 0;
        if($business['business'] == 2 && $total < $business['mianyou']){
            $total = $total + $business['peisongfei'];
            $shipping_amount = $business['peisongfei'];
        }
        //$total = 0.01;
        //检查运费
        /**$shipping_model = new shipping_method_model();
        $shipping_amount = $shipping_model->check_freight($user_id, $shipping_id, $consignee['province'], $cart);
        if(FALSE === $shipping_amount) $this->prompt('error', '计算运费失败');**/
        //创建订单
        $order_model = new order_model();
        $orderid = $order_model->create_order_id();
        $data = array(
            'order_id' => $orderid,
            'user_id' => $user_id,
            //'invite' => $invite,
            'shipping_method' => 0,
            'payment_method' => $payment_method,
            'goods_amount' => $total,
            'shipping_amount' => $shipping_amount,
            'order_amount' => $total,
            'vid' => $vid,
            'memos' => trim(request('remark', '')),
            'created_date' => $_SERVER['REQUEST_TIME'],
            'order_status' => $order_status,
        );

        if($order_model->create($data)) {
            $order_goods_model = new order_goods_model();
            $order_goods_model->add_records($data['order_id'], $goods_list);
            //$order_consignee_model = new order_consignee_model();
            //$order_consignee_model->add_records($data['order_id'], $consignee);

            //更新销量
            if($payment_method == 1){
                $in_id = substr($in, 0, -1);
                $goods_mode = new goods_model();
                $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods SET sell=sell+1 WHERE goods_id IN ($in_id)";
                $goods_mode->query($sql);
                $vcache = vcache::instance();
                $vcache->delete('goods_modelfind_goodsa:2:{i:0;a:1:{s:9:"recommend";i:1;}i:1;i:100;}');//删除首页商品缓存

                //删除购物车中的商品
                //$order_goods_model = new order_goods_model();
                $order_goods = $order_goods_model->find_all(array('order_id' => $orderid));
                $key = $this->_key_user_cart . $user_id;
                $cart_info = $vcache->get($key);
                foreach($order_goods as $g){
                    if (isset($cart_info[$g['goods_id']])) {
                        unset($cart_info[$g['goods_id']]);
                    }
                }
                $vcache->set($key, $cart_info, $this->_cache_year);
            }


            jsonEcho(array('ret' => 0, 'data' => $data));
        } else {
            jsonEcho(array('re' => '1', 'msg' => '创建订单失败，请稍后重试'));
        }
    }
    /**
     * 微信支付
     * order_id:139600005641757
    user_id:1
     */
    public function action_wxpay(){
        /**$_POST['user_id'] = 1;
        $_POST['order_id'] = 139600005641757;**/
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = trim($_POST['order_id']);
        if(!$order_id){
            jsonEcho(array('status' => 3,'err'=>'参数异常！'));
        }
        $order_model = new order_model();
        $order_info = $order_model->find(array('order_id' => $order_id, 'user_id' => $user_id));
        if (!$order_info) {
            jsonEcho(array('status' => 2,'err'=>'没有找到支付订单！'));
        }

        if ($order_info['order_status'] != 1) {
            jsonEcho(array('status' => 1,'err'=>'订单状态异常！'));
        }

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("商品购买_". $order_info['order_id']);
        $input->SetAttach($user_id);
        $input->SetOut_trade_no($order_info['order_id']);
        $input->SetTotal_fee(floatval($order_info['goods_amount'])*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("商品购买_" . $order_info['order_id']);
        $input->SetNotify_url($this->_weixin['notify_url']);//'https://t.kuajiewl.com/wapi/wxpay_notify.html'
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
		file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($order, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=".$order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str."&key=".\WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->memecache_set('prepay_id' . $openid, $order['prepay_id']);
        jsonEcho(array('status' => 0, 'data'=>$arr));
    }
    //***************************
    //  支付回调 接口

    //***************************
    /**
     * {"appid":"wxeefd45e32d9364dc","attach":"\u5546\u54c1\u8d2d\u4e70_304450004808015","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1482407062","nonce_str":"dc1vi8ksynsoz28k57yktu17kwa9i4b8","openid":"o2S1c5X8AxIqgQo3Ita5s4w5_VP4","out_trade_no":"304450004808015","result_code":"SUCCESS","return_code":"SUCCESS","sign":"D9124FD0160789CE1891F920EC24715A","time_end":"20180409162720","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000059201804095207016326"}
     */
    public function action_wxpay_notify(){
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res_xml, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);

        //$ret = json_decode('{"appid":"wxeefd45e32d9364dc","attach":"4","bank_type":"GDB_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1482407062","nonce_str":"ntveeopnra1rcas5vhyvfccbfrwvvhcq","openid":"o2S1c5fM8Eb7Y8Z4udbvB4HLfym4","out_trade_no":"325399002283136","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DDF07CFB35EDBF01215416EDB719C369","time_end":"20180810135936","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000184201808103231496628"}', true);
        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret);
        $file = $path . "wechat_mon_".date("Yn").".txt";
        file_put_contents($file,$content . __LINE__, FILE_APPEND | LOCK_EX);

        //$ret = json_decode('{"appid":"wxeefd45e32d9364dc","attach":"1","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1482407062","nonce_str":"dc1vi8ksynsoz28k57yktu17kwa9i4b8","openid":"o2S1c5X8AxIqgQo3Ita5s4w5_VP4","out_trade_no":"304450004808015","result_code":"SUCCESS","return_code":"SUCCESS","sign":"D9124FD0160789CE1891F920EC24715A","time_end":"20180409162720","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000059201804095207016326"}', true);
        if($ret['result_code'] != 'SUCCESS' || $ret['return_code'] != 'SUCCESS'){
            echo 'fail';
            exit;
        }
        $wechat_arr = array(
            'user_id' => $ret['attach'],
            'out_trade_no' => $ret['out_trade_no'],
            'bank_type' => $ret['bank_type'],
            'cash_fee' => $ret['cash_fee'],
            'total_fee' => $ret['total_fee'],
            'fee_type' => $ret['fee_type'],
            'is_subscribe' => $ret['is_subscribe'],
            'openid' => $ret['openid'],
            'transaction_id' => $ret['transaction_id'],
            'time_end' => $ret['time_end']
        );
        //$wechat_mode = new wechatpay_model();
        //$wechat_mode->create($wechat_arr);
        $data = array();
        $data['out_trade_no'] = $ret['out_trade_no'];
        $result = $this->orderhandle($data);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {


            //删除购物车中的商品
            $order_goods_model = new order_goods_model();
            $order_goods = $order_goods_model->find_all(array('order_id' => $ret['out_trade_no']));
            $key = $this->_key_user_cart . $ret['attach'];
            $vcache = vcache::instance();
            $cart_info = $vcache->get($key);
            foreach($order_goods as $g){
                if (isset($cart_info[$g['goods_id']])) {
                    unset($cart_info[$g['goods_id']]);
                }
            }
            $vcache->set($key, $cart_info, $this->_cache_year);
            $vcache->delete('goods_modelfind_goodsa:2:{i:0;a:1:{s:9:"recommend";i:1;}i:1;i:100;}');//删除首页商品缓存

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            //微信支付更新销量
            $order_goods = $order_goods_model->find_all(array('order_id' => $ret['out_trade_no']), null, 'goods_id');
            $in_id = '';
            foreach($order_goods as $g){
                $in_id .= $g['goods_id'] . ',';
            }
            $in = substr($in_id, 0, -1);
            $goods_mode = new goods_model();
            $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods SET sell=sell+1 WHERE goods_id IN ($in)";
            $goods_mode->query($sql);

            //自动打印订单
            //商品列表
            $condition = array('order_id' => $ret['out_trade_no']);

            $order_model = new order_model();
            $order = $order_model->find($condition);

            //返佣,不是本人，且非0,邀请者是VIP
            $user_nodel = new user_model();
            $user_acctount = new user_account_model();
            $acctount_log = new user_account_log_model();

            $sql = "SELECT invite,vip FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$order['user_id']}'";

            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            $user_data = $user_nodel->query($sql);
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($user_data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


            if($user_data[0]['vip'] > 0 && $user_data[0]['invite'] > 0){
                $sql = "SELECT user_id,invite,vip,md FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$user_data[0]['invite']}'";
                $invite_user_data = $user_nodel->query($sql);
                $invite_user = $invite_user_data[0];
                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($invite_user, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                if($invite_user['user_id'] != $order['user_id'] && $invite_user['vip'] > 0){


                    //更新账户，更新收入日志
                    $sql = "SELECT rake_back FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods WHERE goods_id='{$in}'";
                    $rake_data = $goods_mode->query($sql);
                    $rake = $rake_data[0];
                    $rake_back = $rake['rake_back'];

                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$rake_back,today=today+$rake_back WHERE user_id='{$user_data[0]['invite']}';";
                    $ret = $user_acctount->execute($sql);


                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($invite_user['vip'] == 1){
                            $prize = 2;
                        }
                        if($invite_user['vip'] == 2){
                            $prize = 5;
                        }
                        $time = time();
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data[0]['invite']}', '{$prize}', '{$rake_back}','1', '2', '{$time}');";
                        $acctount_log->execute($sql);
                    }

                }


                //如果是市场总监增加10%收益
                if($invite_user['md'] == 1){
                    $sql = "SELECT king,zun FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$order['user_id']}'";
                    $order_user = $user_nodel->query($sql);

                    $setting_model = new setting_model();
                    $rs = $setting_model->get_config();

                    $vip_settings = json_decode($rs['vip_settings'], true);
                    if($order_user['king'] == 1){
                        $mdback = $vip_settings['king_service_back'] * 0.1;
                    }
                    if($order_user['zun'] == 1){
                        $mdback = $vip_settings['zun_service_back'] * 0.1;
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$mdback,today=today+$mdback WHERE user_id='{$user_data[0]['invite']}';";
                    $ret = $user_acctount->execute($sql);
                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($invite_user['vip'] == 1){
                            $prize = 8;
                        }
                        if($invite_user['vip'] == 2){
                            $prize = 9;
                        }
                        $time = time();
                        if($order['invite'] > 0){
                            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$order['invite']}', '{$prize}', '{$mdback}','1', '2', '{$time}');";
                            $acctount_log->execute($sql);
                        }

                    }
                }
            }


            //$consignee_model = new order_consignee_model();
            //$consignee = $consignee_model->find($condition);

            $goods_list = $order_goods_model->get_goods_list($ret['out_trade_no']);
            //发货列表
            //$carrier_list = $vcache->shipping_carrier_model('indexed_list');
            $shipping_model = new order_shipping_model();
            $shipped_list = $shipping_model->find_all($condition, 'dateline DESC');
            if(!empty($shipped_list)) {
                foreach($shipped_list as &$v) $v['carrier'] = $this->carrier_list[$v['carrier_id']]['name'];
            }


            //$shipped_list = $shipped_list;
            //日志列表
            $log_model = new order_log_model();
            if($log_list = $log_model->find_all($condition, 'dateline DESC')) {
                $this->admin_list = $vcache->admin_model('indexed_list');
                $this->operate_map = $log_model->operate_map;
            }
            $name = '';
            foreach($goods_list as $v){
                $name .= $v['goods_name'] . ' ';
            }
            //打印订单
            /**header("Content-Type: text/html;charset=utf-8");
            $content = "^N1^F1\n";
            $content .= "^B2 " . $consignee['receiver'] . "的订单\n";
            $content .= "名称　　　　   (单价x数量x金额)\n";
            $content .= "--------------------------------\n";
            $name = '';
            foreach($goods_list as $v){
                $name .= $v['goods_name'] . ' ';
                $content .= $v['goods_name'] . " (".$v['goods_price'] . "x" . $v['goods_qty'] . "x" . ($v['goods_price']*$v['goods_qty']) .")\n";
            }
            $content .= "备注：" . $order['memos'] . "\n";

            $content .= "--------------------------------\n";
            $content .= "^H2合计：" . $order['order_amount'] . "元\n";
            $content .= "^H2联系电话：" . $consignee['mobile'] . "\n";
            $content .= "收货人：" . $consignee['receiver'] . "\n";
            $content .= "送货地点：" . $consignee['province'] . $consignee['city'] . $consignee['borough'] . $consignee['address']  . $consignee['menpai'] . "\n";
            $content .= "订餐时间：" . date('Y-m-d H:i:s', $order['created_date']) ."\n";**/
            //$qrlength=chr(strlen('http://open.printcenter.cn'));
            //$content .= "^Q".$qrlength."http://open.printcenter.cn\n";






            //发送模板消息
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['order_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => $name),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/dingdan?currentTab=3&otype=sign';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            /**$setting_model = new setting_model();
            $rs = $setting_model->get_config();
            if($rs['printer'][0] == '' || $rs['printer'][1] == ''){
                jsonEcho(array('ret' => 22, 'msg'=>'请先设置打印机'));
            }
            $result = sendSelfFormatOrderInfo(1, $content, $rs['printer'][0], $rs['printer'][1]);
            $ret = json_decode($result, true);
            if(in_array($ret['responseCode'], array(0,1,2,3))){

            }else{
                file_put_contents($file, var_export($ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            }**/

        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($file, $contents . __LINE__, FILE_APPEND | LOCK_EX);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $out_trade_no = trim($data['out_trade_no']);
        $order_model = new order_model();
        $condition = array('order_id' => $out_trade_no, 'order_status' => 1);
        $order_info = $order_model->find($condition);

        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $order_model->update($condition, array('order_status' => 2, 'payment_date' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {
            //处理优惠券
            /**if ($order_info['vid'] > 0) {
                $user_voucher_model = new user_voucher_model();
                $user_voucher_model->update(array('user_id' => $order_info['user_id']), array('isused' => 1, 'use_time' => time()));
            }**/
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export(666, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }
    /**
     * 微信支付
     * order_id:139600005641757
    user_id:1
     */
    public function action_wxpay_vip(){
        /**$_POST['user_id'] = 1;
        $_POST['order_id'] = 139600005641757;**/
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = trim($_POST['order_id']);
        if(!$order_id){
            jsonEcho(array('status' => 3,'err'=>'参数异常！'));
        }
        $order_vip_model = new order_vip_model();
        $order_info = $order_vip_model->find(array('order_id' => $order_id, 'user_id' => $user_id));
        if (!$order_info) {
            jsonEcho(array('status' => 2,'err'=>'无找到支付订单！'));
        }

        if ($order_info['order_status'] != 1) {
            jsonEcho(array('status' => 1,'err'=>'订单状态异常！'));
        }

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("商品购买_". $order_info['order_id']);
        $input->SetAttach($user_id);
        $input->SetOut_trade_no($order_info['order_id']);
        $input->SetTotal_fee(floatval($order_info['goods_amount'])*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("商品购买_" . $order_info['order_id']);
        $input->SetNotify_url($this->_weixin['vip_notify_url']);//'https://t.kuajiewl.com/wapi/wxpay_notify.html'
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($order, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=".$order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str."&key=".\WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->memecache_set('prepay_id' . $openid, $order['prepay_id']);
        jsonEcho(array('status' => 0, 'data'=>$arr));
    }
    //===========================购买VIP=============================
    /**
     * 支付
     */
    public function action_buy_vip(){
        /**
         * seesionid:xr2V+7YcJ+z6WRQVse6y0Q==
        openid:o2S1c5X8AxIqgQo3Ita5s4w5_VP4
        cart_id:3,
        type:weixin
        aid:11
        remark:
        price:23
        vid:0
         */
        //$_POST['user_id'] = 1;$_POST['cart_id'] = '3,2,';$_POST['aid'] = 2;
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];


        $goods_id = trim($_POST['cart_id']);
        if(!in_array($goods_id, ['vip1','vip2'])){
            jsonEcho(array('ret' => 8, 'msg'=>'商品错误'));
        }
        //$price = $this->_vip_price[$goods_id];
        $setting_model = new setting_model();
        $rs = $setting_model->get_config();

        $vip_settings = json_decode($rs['vip_settings'], true);
        if($goods_id == 'vip1'){
            $price = $vip_settings['king_price'];
        }else{
            $price = $vip_settings['zun_price'];
        }

        //创建订单 0交易取消1等待付款2等待发货3等待签收4交易完成
        $order_vip_model = new order_vip_model();
        $orderid = $order_vip_model->create_order_id();
        $data = array(
            'order_id' => $orderid,
            'user_id' => $user_id,
            'order_status' => 1,
            'vip' => $goods_id,
            'goods_amount' => $price,
            'created_date' => $_SERVER['REQUEST_TIME'],
        );

        if($order_vip_model->create($data)) {
            jsonEcho(array('ret' => 0, 'data' => $data));
        } else {
            jsonEcho(array('re' => '1', 'msg' => '创建订单失败，请稍后重试'));
        }
    }
    public function action_wxpay_notify_vip(){
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res_xml, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);

        //$ret = json_decode('{"appid":"wx06ba160628f3511c","attach":"2","bank_type":"CFT","cash_fee":"2","fee_type":"CNY","is_subscribe":"N","mch_id":"1517652191","nonce_str":"2l6zjbm5e2aaquqbmzuq82b00mq1summ","openid":"owpeA4n4K8QVJvpN2JUC8KU8MyHc","out_trade_no":"623160000126305","result_code":"SUCCESS","return_code":"SUCCESS","sign":"B3818C6E2AC133C793814BEFC9DCA5D3","time_end":"20181212153612","total_fee":"2","trade_type":"JSAPI","transaction_id":"4200000233201812123909134589"}', true);
        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret);
        $file = $path . "wechat_mon_".date("Yn").".txt";
        file_put_contents($file,$content . __LINE__, FILE_APPEND | LOCK_EX);

        //$ret = json_decode('{"appid":"wx06ba160628f3511c","attach":"3","bank_type":"CFT","cash_fee":"2","fee_type":"CNY","is_subscribe":"N","mch_id":"1517652191","nonce_str":"k6imgsr9s24e88oqxpgalu75yad7imvy","openid":"owpeA4t4AFhlOMemSQ3o6TJshIag","out_trade_no":"625610004800154","result_code":"SUCCESS","return_code":"SUCCESS","sign":"6A7C1E8720B111AC0B780FCC47EE8D4F","time_end":"20181213160553","total_fee":"2","trade_type":"JSAPI","transaction_id":"4200000213201812133380408600"}', true);
        if($ret['result_code'] != 'SUCCESS' || $ret['return_code'] != 'SUCCESS'){
            echo 'fail';
            exit;
        }
        $wechat_arr = array(
            'user_id' => $ret['attach'],
            'out_trade_no' => $ret['out_trade_no'],
            'bank_type' => $ret['bank_type'],
            'cash_fee' => $ret['cash_fee'],
            'total_fee' => $ret['total_fee'],
            'fee_type' => $ret['fee_type'],
            'is_subscribe' => $ret['is_subscribe'],
            'openid' => $ret['openid'],
            'transaction_id' => $ret['transaction_id'],
            'time_end' => $ret['time_end']
        );
        //$wechat_mode = new wechatpay_model();
        //$wechat_mode->create($wechat_arr);
        $data = array();
        $data['out_trade_no'] = $ret['out_trade_no'];
        $result = $this->orderhandle_vip($data);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            $condition = array('order_id' => $ret['out_trade_no']);

            $order_vip_model = new order_vip_model();
            $order = $order_vip_model->find($condition);
            $vip = 0;
            $setting_model = new setting_model();
            $rs = $setting_model->get_config();

            $vip_settings = json_decode($rs['vip_settings'], true);
            $vip_back = $vip_back2 = 0;
            if($order['vip'] == 'vip1'){
                $vip = 1;
            }elseif($order['vip'] == 'vip2'){
                $vip = 2;
            }

            $user_model = new user_model();
            $affected = $user_model->update(array('user_id' => $ret['attach']), array('vip' => $vip));
            if($affected) {
                file_put_contents($file, var_export('更新用户vip成功', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            } else {
                file_put_contents($file, var_export('更新用户vip失败', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            }
            file_put_contents($file, var_export(array('user_id' => $ret['attach']), true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            file_put_contents($file, var_export(array('vip' => $vip), true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            file_put_contents($file, var_export($user_model->dump_sql(), true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            //========邀请人加收益start=======
            //更新账户，更新收入日志

            //一级
            $time = time();
            $user_acctount = new user_account_model();
            $acctount_log = new user_account_log_model();
            $user_data = $user_model->find(['user_id' => $ret['attach']]);

            $invite_user_data = $user_model->find(['user_id' => $user_data['invite']]);
            //print_r($invite_user_data['vip']);print_r($order['vip']);
            //根据邀请人的VIP等级返佣
            if($invite_user_data['vip'] == 1 || $order['vip']  == 'vip1'){
                $vip_back = $vip_settings['king_zhitui'];
                //$vip_back2 = $vip_settings['king_zhitui2'];
            }else if($invite_user_data['vip'] == 2 && $order['vip'] == 'vip2'){
                $vip_back = $vip_settings['zun_zhitui'];
                //$vip_back2 = $vip_settings['zun_zhitui2'];
            }
            if($invite_user_data['vip'] > 0){
                if($user_data['invite'] > 0 && $user_data['invite'] != $user_data['user_id']){

                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back,today=today+$vip_back WHERE user_id='{$user_data['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($vip == 1){
                            $prize = 0;
                        }
                        if($vip == 2){
                            $prize = 3;
                        }
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data['invite']}', '{$prize}', '{$vip_back}','1', '0', '{$time}');";
                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }


                //二级
                $user_data2 = $user_model->find(['user_id' => $user_data['invite']]);
                if($user_data2['invite'] > 0 && $user_data2['vip'] > 0){
                    //if($user_data2['vip'] == 1 || $order['vip']  == 'vip1'){
                        //$vip_back = $vip_settings['king_zhitui'];
                    $vip_back2 = $vip_settings['king_zhitui2'];
                    if(($user_data2['vip'] == 2 && $order['vip'] == 'vip2') || $user_data['vip'] == 2 && $order['vip'] == 'vip2'){
                        //$vip_back = $vip_settings['zun_zhitui'];
                        $vip_back2 = $vip_settings['zun_zhitui2'];
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back2,today=today+$vip_back2 WHERE user_id='{$user_data2['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($vip == 1){
                            $prize = 0;
                        }
                        if($vip == 2){
                            $prize = 4;
                        }
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data2['invite']}', '6', '{$vip_back2}','1', '4', '{$time}');";

                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }


                //尊贵VIP会员直推20个尊贵VIP会员升级为市场总监，在团队伞下每新增一个尊贵VIP奖励20元，每新增一个金卡VIP奖励2元
                $count = $user_model->find_count(['invite' => $user_data['invite']]);
                if($count >= 20){
                    //不是市场总监则更新
                    $user_data3 = $user_model->find(['user_id' => $user_data['invite']]);
                    if($user_data3['md'] == 0){
                        $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user SET md='1' WHERE user_id='{$user_data3['user_id']}';";
                        $user_model->execute($sql);
                    }
                    if($vip == 1){
                        $addmoney = $vip_settings['king_md'];
                        $prize = 6;
                    }
                    if($vip == 2){
                        $addmoney = $vip_settings['zun_md'];
                        $prize = 7;
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$addmoney,today=today+$addmoney WHERE user_id='{$user_data3['user_id']}';";
                    $ret = $user_acctount->execute($sql);
                    //插入日志
                    if($ret){
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data3['user_id']}', '{$prize}', '{$addmoney}','1', '2', '{$time}');";
                        $acctount_log->execute($sql);
                    }
                }
            }

            //========邀请人加收益end=======


            //发送模板消息
            //$tid = 'hDuWaRojW0-5vKgDMenMjmGv-0SmqDTioJln9PNUEXY';
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            /**$data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => '购买vip' . $order['vip']),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
                'keyword7' => array('value' => '购买vip服务'),
                'keyword8' => array('value' => ''),
            ];**/
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => '购买vip' . $order['vip']),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/user';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($file, $contents . __LINE__, FILE_APPEND | LOCK_EX);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle_vip($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $out_trade_no = trim($data['out_trade_no']);
        $order_vip_model = new order_vip_model();
        $condition = array('order_id' => $out_trade_no, 'order_status' => 1);
        $order_info = $order_vip_model->find($condition);

        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $order_vip_model->update($condition, array('order_status' => 2, 'payment_date' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {

            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }
    //===========================购买VIP=============================



    /**
     * 微信支付
     * order_id:139600005641757
    user_id:1
     */
    public function action_wxpay_guwen(){
        /**$_POST['user_id'] = 1;
        $_POST['order_id'] = 139600005641757;**/
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = trim($_POST['order_id']);
        if(!$order_id){
            jsonEcho(array('status' => 3,'err'=>'参数异常！'));
        }
        $order_vip_model = new order_guwen_model();
        $order_info = $order_vip_model->find(array('order_id' => $order_id, 'user_id' => $user_id));
        if (!$order_info) {
            jsonEcho(array('status' => 2,'err'=>'无找到支付订单！'));
        }

        if ($order_info['order_status'] != 1) {
            jsonEcho(array('status' => 1,'err'=>'订单状态异常！'));
        }

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("购买专家顾问服务_". $order_info['order_id']);
        $input->SetAttach($user_id);
        $input->SetOut_trade_no($order_info['order_id']);
        $input->SetTotal_fee(floatval($order_info['goods_amount'])*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("购买专家顾问服务_" . $order_info['order_id']);
        $input->SetNotify_url($this->_weixin['vip_notify_url']);//'https://t.kuajiewl.com/wapi/wxpay_notify.html'
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($order, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=".$order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str."&key=".\WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->memecache_set('prepay_id' . $openid, $order['prepay_id']);
        jsonEcho(array('status' => 0, 'data'=>$arr));
    }
    //===========================购买VIP=============================
    /**
     * 支付
     */
    public function action_buy_guwen(){
        /**
         * seesionid:xr2V+7YcJ+z6WRQVse6y0Q==
        openid:o2S1c5X8AxIqgQo3Ita5s4w5_VP4
        cart_id:3,
        type:weixin
        aid:11
        remark:
        price:23
        vid:0
         */
        //$_POST['user_id'] = 1;$_POST['cart_id'] = '3,2,';$_POST['aid'] = 2;
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];


        //$price = $this->_vip_price[$goods_id];
        $setting_model = new setting_model();
        $rs = $setting_model->get_config();

        $vip_settings = json_decode($rs['vip_settings'], true);
        $price = $vip_settings['guwen_price'];

        //创建订单 0交易取消1等待付款2等待发货3等待签收4交易完成
        $order_vip_model = new order_guwen_model();
        $orderid = $order_vip_model->create_order_id();
        $data = array(
            'order_id' => $orderid,
            'user_id' => $user_id,
            'order_status' => 1,
            'goods_amount' => $price,
            'created_date' => $_SERVER['REQUEST_TIME'],
        );

        if($order_vip_model->create($data)) {
            jsonEcho(array('ret' => 0, 'data' => $data));
        } else {
            jsonEcho(array('re' => '1', 'msg' => '创建订单失败，请稍后重试'));
        }
    }
    public function action_wxpay_notify_guwen(){
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res_xml, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);

        //$ret = json_decode('{"appid":"wx06ba160628f3511c","attach":"2","bank_type":"CFT","cash_fee":"2","fee_type":"CNY","is_subscribe":"N","mch_id":"1517652191","nonce_str":"2l6zjbm5e2aaquqbmzuq82b00mq1summ","openid":"owpeA4n4K8QVJvpN2JUC8KU8MyHc","out_trade_no":"623160000126305","result_code":"SUCCESS","return_code":"SUCCESS","sign":"B3818C6E2AC133C793814BEFC9DCA5D3","time_end":"20181212153612","total_fee":"2","trade_type":"JSAPI","transaction_id":"4200000233201812123909134589"}', true);
        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret);
        $file = $path . "wechat_mon_".date("Yn").".txt";
        file_put_contents($file,$content . __LINE__, FILE_APPEND | LOCK_EX);

        //$ret = json_decode('{"appid":"wx06ba160628f3511c","attach":"3","bank_type":"CFT","cash_fee":"2","fee_type":"CNY","is_subscribe":"N","mch_id":"1517652191","nonce_str":"k6imgsr9s24e88oqxpgalu75yad7imvy","openid":"owpeA4t4AFhlOMemSQ3o6TJshIag","out_trade_no":"625610004800154","result_code":"SUCCESS","return_code":"SUCCESS","sign":"6A7C1E8720B111AC0B780FCC47EE8D4F","time_end":"20181213160553","total_fee":"2","trade_type":"JSAPI","transaction_id":"4200000213201812133380408600"}', true);
        if($ret['result_code'] != 'SUCCESS' || $ret['return_code'] != 'SUCCESS'){
            echo 'fail';
            exit;
        }
        $wechat_arr = array(
            'user_id' => $ret['attach'],
            'out_trade_no' => $ret['out_trade_no'],
            'bank_type' => $ret['bank_type'],
            'cash_fee' => $ret['cash_fee'],
            'total_fee' => $ret['total_fee'],
            'fee_type' => $ret['fee_type'],
            'is_subscribe' => $ret['is_subscribe'],
            'openid' => $ret['openid'],
            'transaction_id' => $ret['transaction_id'],
            'time_end' => $ret['time_end']
        );
        //$wechat_mode = new wechatpay_model();
        //$wechat_mode->create($wechat_arr);
        $data = array();
        $data['out_trade_no'] = $ret['out_trade_no'];
        $result = $this->orderhandle_guwen($data);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            $condition = array('order_id' => $ret['out_trade_no']);

            $order_vip_model = new order_guwen_model();
            $order = $order_vip_model->find($condition);
            $setting_model = new setting_model();
            $rs = $setting_model->get_config();

            $vip_settings = json_decode($rs['vip_settings'], true);
            $vip_back = $vip_back2 = 0;

            $user_model = new user_model();
            file_put_contents($file, var_export(array('user_id' => $ret['attach']), true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            //========邀请人加收益start=======
            //更新账户，更新收入日志

            //一级
            $time = time();
            $user_acctount = new user_account_model();
            $acctount_log = new user_account_log_model();
            $user_data = $user_model->find(['user_id' => $ret['attach']]);

            $invite_user_data = $user_model->find(['user_id' => $user_data['invite']]);
            //print_r($invite_user_data['vip']);print_r($order['vip']);
            //根据邀请人的VIP等级返佣
            if($invite_user_data['vip'] == 1){
                $vip_back = $vip_settings['king_zhitui'];
                $prize = 0;
                //$vip_back2 = $vip_settings['king_zhitui2'];
            }else if($invite_user_data['vip'] == 2){
                $vip_back = $vip_settings['zun_zhitui'];
                $prize = 3;
                //$vip_back2 = $vip_settings['zun_zhitui2'];
            }
            if($invite_user_data['vip'] > 0){
                if($user_data['invite'] > 0 && $user_data['invite'] != $user_data['user_id']){

                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back,today=today+$vip_back WHERE user_id='{$user_data['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data['invite']}', '{$prize}', '{$vip_back}','1', '0', '{$time}');";
                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }


                //二级
                $user_data2 = $user_model->find(['user_id' => $user_data['invite']]);
                if($user_data2['invite'] > 0){
                    //if($user_data2['vip'] == 1 || $order['vip']  == 'vip1'){
                    //$vip_back = $vip_settings['king_zhitui'];
                    $prize = 0;
                    $vip_back2 = $vip_settings['king_zhitui2'];
                    if($user_data['vip'] == 2){
                        //$vip_back = $vip_settings['zun_zhitui'];
                        $prize = 4;
                        $vip_back2 = $vip_settings['zun_zhitui2'];
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back2,today=today+$vip_back2 WHERE user_id='{$user_data2['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data2['invite']}', '6', '{$vip_back2}','1', '4', '{$time}');";

                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }
            }

            //========邀请人加收益end=======


            //发送模板消息
            //$tid = 'hDuWaRojW0-5vKgDMenMjmGv-0SmqDTioJln9PNUEXY';
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            /**$data = [
            'keyword1' => array('value' =>  $ret['out_trade_no']),
            'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
            'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
            'keyword4' => array('value' => '购买vip' . $order['vip']),
            'keyword5' => array('value' => date('Y-m-d H:i:s')),
            'keyword6' => array('value' => '微信支付'),
            'keyword7' => array('value' => '购买vip服务'),
            'keyword8' => array('value' => ''),
            ];**/
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => '购买专家顾问服务'),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/user';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($file, $contents . __LINE__, FILE_APPEND | LOCK_EX);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle_guwen($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $out_trade_no = trim($data['out_trade_no']);
        $order_vip_model = new order_vip_model();
        $condition = array('order_id' => $out_trade_no, 'order_status' => 1);
        $order_info = $order_vip_model->find($condition);

        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $order_vip_model->update($condition, array('order_status' => 2, 'payment_date' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {
            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }
    //===========================购买VIP=============================

    //构建字符串
    private function ToUrlParams($urlObj){
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    /**判断用户是否登录
     * @param $openid
     * @param $seesionid
     */
    private function wechat_is_login($openid, $seesionid){
        $openid = trim($openid);
        $sessionId = trim($seesionid);
        if (!$openid || !$sessionId) {
            return array('ret' => 10, 'msg'=>'授权失败！');
        }
        //$key = $this->_key_user . $openid;
        //$vcache = vcache::instance();
        //$uinfo = $vcache->get($key);


       // $uinfo = [];
        //if(empty($uinfo) || $sessionId != $uinfo['sessionid']){
            //$vcache->delete($key);

            $user_model = new user_model();
            $user = $user_model->find(array('openid' => $openid), null, 'user_id,invite,username,openid,mobile,avatar,status,sex,vip,bank,bank_name,reg_time');
            if(!empty($user)){
                $user['sessionid'] = $seesionid;
                $user['session'] = [];
                $free_model = new free_model();
                $month = strtotime(date('Y-m'));

                if($user['vip'] == 1){
                    $free_first = $free_model->find(['user_id' => $user['user_id'], 'vip' => 1]);
                    $free_info = $free_model->find(['user_id' => $user['user_id'], 'vip' => 1, 'month' => $month, 'status' => 2]);
                }else if($user['vip'] == 2){
                    $free_first = $free_model->find(['user_id' => $user['user_id'], 'vip' => 2]);
                    $free_info = $free_model->find(['user_id' => $user['user_id'], 'vip' => 2, 'month' => $month, 'status' => 2]);
                }
                //$free_info = $free_model->find(['user_id' => $user['user_id'], 'month' => $month, 'status' => 2]);
                //$sql = "SELECT count(id) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}free WHERE user_id='{$user['user_id']}' AND month='{$month}' AND day<='{$end}';";
                //$count = $user_share->execute($sql);

                $user['receive'] = 0;
                if(!empty($free_first)){
                    $user['receive'] = 1;
                }
                if(!empty($free_info)){
                    $user['receive'] = 1;
                }

                //$vcache->set($key, $user, 60);
                return array('ret' => 0, 'data' => $user);
            }

            return array('ret' => 9,'msg'=>'用户非法！');
        //}
        $uinfo['session'] = [];
        return array('ret' => 0, 'data' => $uinfo);
    }
    /**
     * 用户订单统计 0交易取消1等待付款2等待发货3等待签收4交易完成
     */
    public function action_user_order(){
        //$_POST['openid'] = 'o2S1c5X8AxIqgQo3Ita5s4w5_VP4';$_POST['seesionid']='7ycLLDik9AiGu19OSxl+Ug==';

        /**$_POST = array (
            'uid' => '1',
            'pid' => '4',
            'num' => '1',
            'seesionid' => '7VAKn6Po1hY0/Eq+wcr8/w==',
            'openid' => 'o2S1c5aDwnLAtFJuMlz2KgfW-XN8',
        );**/
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);//dieEcho($uinfo);
        //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/a.txt', var_export($uinfo, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        //$setting_model = new setting_model();
        //$rs = $setting_model->get_config();
        $paysql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order WHERE user_id = {$user_id} AND order_status = 1";
        $shipsql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order WHERE user_id = {$user_id} AND order_status = 2";
        $signsql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order WHERE user_id = {$user_id} AND order_status = 3";
        $reviewsql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order WHERE user_id = {$user_id} AND order_status = 4 AND order_id in (SELECT order_id FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order_goods WHERE is_reviewed = 0)";

        $order_model = new order_model();
        $pay = $order_model->query($paysql);
        $ship = $order_model->query($shipsql);
        $sign = $order_model->query($signsql);
        $review= $order_model->query($reviewsql);

        $user_account = new user_account_model();
        $money = $user_account->find(['user_id' => $user_id], null, 'balance,today,cashed');
        /**if(empty($money)){
            $money = ['balance' => '0.00', 'today' => '0.00', 'cashed' => '0.00'];
            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account (`user_id`, `balance`, `today`,`cashed`)
                     VALUES ('{$user_id}', '0.00', '0.00','0.00');";
            $user_account->execute($sql);
        }**/

        $fields = 'user_id,invite';
        $user_model = new user_model();
        $lv1count = $lv2count = 0;
        if($uinfo['data']['vip'] > 0){
            $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE invite='{$user_id}' AND vip>0";
            //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/a.txt', var_export($sql, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            $data = $user_model->query($sql);

            $level2 = '';
            $lv1count = 0;
            $lv2count = 0;
            foreach($data as $k => $v){
                if($data[$k]['invite']){
                    $level2 .= $data[$k]['user_id'] . ',';
                }
                $lv1count++;
            }

            if($level2 != ''){
                $level2 = substr($level2, 0, -1);
                $sql = "SELECT count(user_id) as count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE invite in({$level2})";
                $lvdata = $user_model->query($sql);
                $lv2count = $lvdata[0]['count'];
            }

        }

        jsonEcho(array('ret' => 0, 'data' => array('money' => $money, 'vip' => $uinfo['data']['vip'], 'bank' => ($uinfo['data']['bank'] == null) ? '' : $uinfo['data']['bank'], 'lv1' => $lv1count,'lv2' => $lv2count, 'pay' => $pay[0]['count'], 'ship' => $ship[0]['count'], 'sign' => $sign[0]['count'], 'review' => $review[0]['count'])));

    }
    /**
     * 管理员订单列表
     */
    public function action_order_list_admin(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }

        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        if($rs['openid'] != $openid){
            jsonEcho(array('ret' => 2, 'msg'=>'你不是管理员'));
        }

        $order_type = trim($_POST['order_type']);
        if(!in_array($order_type, array('all', 'pay', 'ship', 'sign', 'review'))){
            jsonEcho(array('ret' => 9, 'msg'=>'参数错误'));
        }
        $sql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order";
        $where = "WHERE 1";
        switch($order_type)
        {
            case 'pay': $where .= " AND order_status = 1"; break;

            case 'ship': $where .= " AND (order_status = 2)"; break;

            case 'sign': $where .= " AND order_status = 3"; break;

            case 'review': $where .= " AND order_status = 4 AND order_id in (SELECT order_id FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order_goods WHERE is_reviewed = 0)"; break;
        }

        $res = array('ret' => '8', 'msg' => '暂无订单');
        $order_model = new order_model();
        $total = $order_model->query("{$sql} {$where}");
        if($total[0]['count'] > 0){
            //$limit = $order_model->set_limit(array(request('page', 1), request('pernum', 10)), $total[0]['count']);
            $page = request('page', 1);
            if($page < 1){
                $num = 0;
            }else{
                $num = ($page - 1) * 10;
            }
            $limit = 'LIMIT ' . $num .',10';
            $sql = "SELECT * FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order {$where} ORDER BY id DESC {$limit}";
            if($list = $order_model->query($sql)){
                $order_goods_model = new order_goods_model();
                foreach($list as $k => $v){
                    $progress = $order_model->get_user_order_progress($v['order_status'], $v['payment_method']);
                    $v['progress'] = array_pop($progress);
                    //$v['goods_list'] = $order_goods_model->get_goods_list($v['order_id']);
                    $goods_list = $order_goods_model->get_goods_list($v['order_id']);
                    foreach($goods_list as $kk => $g){
                        $list[$k]['ginfo'][$kk]['goods_id'] = $g['goods_id'];
                        $list[$k]['ginfo'][$kk]['goods_name'] = $g['goods_name'];
                        $list[$k]['ginfo'][$kk]['goods_image'] = $g['goods_image'];
                        $list[$k]['ginfo'][$kk]['now_price'] = $g['goods_price'];
                        $list[$k]['ginfo'][$kk]['goods_qty'] = $g['goods_qty'];
                        $list[$k]['ginfo'][$kk]['created_date'] = date('Y-m-d H:i:s', $v['created_date']);
                    }
                }
                $res = array('ret' => 0, 'data' => $list);
            }
        }
        jsonEcho($res);
    }
    /**
     * 管理员打印订单
     */
    public function action_print_order(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }

        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        if($rs['openid'] != $openid){
            jsonEcho(array('ret' => 2, 'msg'=>'你不是管理员'));
        }
        if($rs['printer'][0] == '' || $rs['printer'][1] == ''){
            jsonEcho(array('ret' => 22, 'msg'=>'请先设置打印机'));
        }

        $condition = array('order_id' => request('order_id', ''));
        $order_model = new order_model();
        if($order = $order_model->find($condition)) {
            $vcache = vcache::instance();
            //$payment_map = $vcache->payment_method_model('indexed_list');
            $shipping_map = $vcache->shipping_method_model('indexed_list');
            $order['payment_method_name'] = '微信支付';
            $order['shipping_method_name'] = '线下配送';

            $consignee_model = new order_consignee_model();
            $consignee = $consignee_model->find($condition);
            //$order = $order;
            $status_map = $order_model->status_map;
            //用户信息
            //$user_model = new user_model();
            //$user = $user_model->find(array('user_id' => $order['user_id']));
            //商品列表
            $order_goods_model = new order_goods_model();
            $goods_list = $order_goods_model->get_goods_list($condition['order_id']);
            //发货列表
            $carrier_list = $vcache->shipping_carrier_model('indexed_list');
            $shipping_model = new order_shipping_model();
            $shipped_list = $shipping_model->find_all($condition, 'dateline DESC');
            if(!empty($shipped_list)) {
                foreach($shipped_list as &$v) $v['carrier'] = $this->carrier_list[$v['carrier_id']]['name'];
            }
            //$shipped_list = $shipped_list;
            //日志列表
            $log_model = new order_log_model();
            if($log_list = $log_model->find_all($condition, 'dateline DESC')) {
                $this->admin_list = $vcache->admin_model('indexed_list');
                $this->operate_map = $log_model->operate_map;
            }
            //打印订单
            header("Content-Type: text/html;charset=utf-8");
            $content = "^N1^F1\n";
            $content .= "^B2 " . $consignee['receiver'] . "的订单\n";
            $content .= "名称　　　　   (单价x数量x金额)\n";
            $content .= "--------------------------------\n";
            $name = '';
            foreach($goods_list as $v){
                $content .= $v['goods_name'] . " (".$v['goods_price'] . "x" . $v['goods_qty'] . "x" . ($v['goods_price']*$v['goods_qty']) .")\n";
            }
            $content .= "备注：" . $order['memos'] . "\n";
            //print_r($order);
            //dieEcho($goods_list);
            $content .= "--------------------------------\n";
            $content .= "^H2合计：" . $order['order_amount'] . "元\n";
            $content .= "^H2联系电话：" . $consignee['mobile'] . "\n";
            $content .= "收货人：" . $consignee['receiver'] . "\n";
            $content .= "送货地点：" . $consignee['province'] . $consignee['city'] . $consignee['borough'] . $consignee['address'] . $consignee['menpai'] . "\n";
            $content .= "订餐时间：" . date('Y-m-d H:i:s', $order['created_date']) ."\n";
            //$qrlength=chr(strlen('http://open.printcenter.cn'));
            //$content .= "^Q".$qrlength."http://open.printcenter.cn\n";
            $result = sendSelfFormatOrderInfo(1, $content, $rs['printer'][0], $rs['printer'][1]);
            $ret = json_decode($result, true);
            if(in_array($ret['responseCode'], array(0,1,2,3))){
                jsonEcho(array('ret' => 0));
            }
            jsonEcho(array('ret' => 8, 'msg' => $ret['msg']));
        }
        jsonEcho(array('ret' => 7, 'msg' => '订单不存在'));
    }

    /**
     * 订单操作
     */
    public function action_operate(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }

        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        if($rs['openid'] != $openid){
            jsonEcho(array('ret' => 2, 'msg'=>'你不是管理员'));
        }

        $order_id = request('order_id', '');
        $condition = array('order_id' => $order_id);
        $status = (int)$_POST['status'];
        $order_model = new order_model();
        if($order = $order_model->find($condition)){
            switch(request('step')){
                case 'consignee':
                    if($order['order_status'] == 1 || $order['order_status'] == 2){
                        $data = array(
                            'receiver' => trim(request('receiver', '')),
                            'province' => trim(request('province', '')),
                            'city' => trim(request('city', '')),
                            'borough' => trim(request('borough', '')),
                            'address' => trim(request('address', '')),
                            'zip' => trim(request('zip', '')),
                            'mobile' => trim(request('mobile', '')),
                        );
                        $consignee_model = new order_consignee_model();
                        $verifier = $consignee_model->verifier($data);
                        if(TRUE === $verifier) {
                            if($consignee_model->update(array('order_id' => $order_id), $data) > 0){
                                $cause = trim(request('cause', ''));
                                $log_model = new order_log_model();
                                $log_model->record($order_id, 'consignee', $cause);
                            } else {
                                jsonEcho(array('ret' => 11, 'msg' => '网络错误'));
                            }
                        } else {
                            jsonEcho(array('ret' => 13, 'msg' => '网络错误'));
                        }
                    } else {
                        jsonEcho(array('ret' => 12, 'msg' => '网络错误'));
                    }

                    break;

                case 'amount': //更改金额

                    if($order['order_status'] == 1) {
                        $order_amount = sprintf('%.2f', abs(request('order_amount', 0, 'post')));
                        if($order_model->update($condition, array('order_amount' => $order_amount)) > 0) {
                            $cause = request('cause', '', 'post');
                            $log_model = new order_log_model();
                            $log_model->record($order_id, 'amount', $cause);
                        } else {
                            jsonEcho(array('ret' => 9, 'msg' => '网络错误'));
                        }
                    } else {
                        jsonEcho(array('ret' => 8, 'msg' => '网络错误'));
                    }

                    break;

                case 'cancel': //取消交易

                    if($order['order_status'] == 1) {
                        if($order_model->update($condition, array('order_status' => 0)) > 0) {
                            $order_goods_model = new order_goods_model();
                            $order_goods_model->restocking($order_id);
                            $cause = trim(request('cause', ''));
                            $log_model = new order_log_model();
                            $log_model->record($order_id, 'cancel', $cause);
                        } else {
                            jsonEcho(array('ret' => 7, 'msg' => '网络错误'));
                        }
                    } else {
                        jsonEcho(array('ret' => 6, 'msg' => '网络错误'));
                    }

                    break;

                case 'resume': //恢复被取消交易

                    if($order['order_status'] == 0) {
                        if($order_model->update($condition, array('order_status' => 1)) > 0) {
                            $order_goods_model = new order_goods_model();
                            $order_goods_model->restocking($order_id, 'decr');
                            $cause = trim(request('cause', ''));
                            $log_model = new order_log_model();
                            $log_model->record($order_id, 'resume', $cause);
                        } else {
                            jsonEcho(array('ret' => 5, 'msg' => '网络错误'));
                        }
                    }else{
                        jsonEcho(array('ret' => 4, 'msg' => '网络错误'));
                    }

                    break;
                case 'shipping':
                    //0正在配送1取消发货
                    if($order['order_status'] >= 2 || ($order['order_status'] != 0)){
                        if($status == 0){
                            $order_model->update(array('order_id' => $order_id), array('order_status' => 3));
                        }else{
                            $order_model->update(array('order_id' => $order_id), array('order_status' => 2));
                        }
                    }else {
                        jsonEcho(array('ret' => 3, 'msg' => '网络错误'));
                    }

                    break;
                case 'complete':
                    //0正在配送1取消发货
                    if($order['order_status'] >= 2 || ($order['order_status'] != 0)){
                        if($status == 0){
                            $order_model->update(array('order_id' => $order_id), array('order_status' => 4));
                        }else{
                            $order_model->update(array('order_id' => $order_id), array('order_status' => 3));
                        }
                    }else {
                        jsonEcho(array('ret' => 2, 'msg' => '网络错误'));
                    }

                    break;
            }
            jsonEcho(array('ret' => 0));
        }else {
            jsonEcho(array('ret' => 1, 'msg' => '订单不存在'));
        }
    }
    /**
     * 用户售后列表
     */
    public function action_order_refund(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $aftersales_model = new aftersales_model();
        $list = $aftersales_model->get_user_aftersales_wx($user_id, array(request('page', 1), request('pernum', 10)));
        //dieEcho($aftersales_model->dump_sql());
        if($list) {
            $res = array('ret' => 0, 'data' => $list, 'paging' => $aftersales_model->page);
        }else {
            $res = array('ret' => 1);
        }
        jsonEcho($res);
    }
    /**
     * 管理员用户售后列表
     */
    public function action_order_refund_admin(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        if($rs['openid'] != $openid){
            jsonEcho(array('ret' => 9, 'msg'=>'你不是管理员'));
        }

        $aftersales_model = new aftersales_model();
        $list = $aftersales_model->get_user_aftersales_wx_admin( array(request('page', 1), request('pernum', 10)));
        //dieEcho($aftersales_model->dump_sql());
        if($list) {
            $res = array('ret' => 0, 'data' => $list, 'paging' => $aftersales_model->page);
        }else {
            $res = array('ret' => 1 , 'msg' => '没有了');
        }
        jsonEcho($res);
    }

    /**
     * 设置售后状态
     */
    public function action_refund_status(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        if($rs['openid'] != $openid){
            jsonEcho(array('ret' => 9, 'msg'=>'你不是管理员'));
        }

        $order_id = (int)request('order_id', 0);
        $status = (int)request('status', 0);
        $aftersales_model = new aftersales_model();
        if($aftersales_model->update(array('order_id' => $order_id), array('status' => $status)) > 0) {
            $res = array('ret' => 0);
        }else {
            $res = array('ret' => 1 , 'msg' => '操作失败');
        }
        jsonEcho($res);
    }
    /**
     * 用户退换货
     */
    public function action_orders_customer_service(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = bigintstr(request('id'));
        $aftersales_model = new aftersales_model();
        if($aftersales_model->find(array('user_id' => $user_id, 'order_id' => $order_id))) {
            die(json_encode(array('ret' => 5, 'err' => '已申请过了售后')));
        }

        $data = array
        (
            'user_id' => $user_id,
            'order_id' => $order_id,
            'type' => (int)request('type', 0),
            'cause' => trim(strip_tags(request('back_remark', ''))),
            'created_date' => $_SERVER['REQUEST_TIME'],
            'status' => 0,
        );

        $verifier = $aftersales_model->verifier($data);
        if(TRUE === $verifier) {
            if($aftersales_model->create($data)) {
                $res = array('ret' => '0');
            }else {
                $res = array('ret' => 2, 'err' => '提交失败,请稍后重试');
            }
        }else {
            $res = array('ret' => 3, 'err' => $verifier[0]);
        }
        jsonEcho($res);
    }
    /**
     * 用户订单列表
     */
    public function action_order_list(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_type = trim($_POST['order_type']);
        if(!in_array($order_type, array('all', 'pay', 'ship', 'sign', 'review'))){
            jsonEcho(array('ret' => 9, 'msg'=>'参数错误'));
        }
        $sql = "SELECT COUNT(1) AS count FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order";
        $where = "WHERE user_id = {$user_id}";
        switch($order_type)
        {
            case 'pay': $where .= " AND order_status = 1"; break;

            case 'ship': $where .= " AND (order_status = 2)"; break;

            case 'sign': $where .= " AND order_status = 3"; break;

            case 'review': $where .= " AND order_status = 4 AND order_id in (SELECT order_id FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order_goods WHERE is_reviewed = 0)"; break;
        }

        $res = array('ret' => '8', 'msg' => '暂无订单');
        $order_model = new order_model();
        $total = $order_model->query("{$sql} {$where}");
        if($total[0]['count'] > 0){
            $limit = $order_model->set_limit(array(request('page', 1), request('pernum', 10)), $total[0]['count']);
            $sql = "SELECT * FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}order {$where} ORDER BY id DESC {$limit}";
            if($list = $order_model->query($sql)){
                $order_goods_model = new order_goods_model();
                foreach($list as $k => $v){
                    $progress = $order_model->get_user_order_progress($v['order_status'], $v['payment_method']);
                    $v['progress'] = array_pop($progress);
                    //$v['goods_list'] = $order_goods_model->get_goods_list($v['order_id']);
                    $goods_list = $order_goods_model->get_goods_list($v['order_id']);
                    foreach($goods_list as $kk => $g){
                        $list[$k]['ginfo'][$kk]['goods_id'] = $g['goods_id'];
                        $list[$k]['ginfo'][$kk]['goods_name'] = $g['goods_name'];
                        $list[$k]['ginfo'][$kk]['goods_image'] = $g['goods_image'];
                        $list[$k]['ginfo'][$kk]['now_price'] = $g['goods_price'];
                        $list[$k]['ginfo'][$kk]['goods_qty'] = $g['goods_qty'];
                        $list[$k]['ginfo'][$kk]['created_date'] = date('Y-m-d H:i:s', $v['created_date']);
                    }
                }
                $res = array('ret' => 0, 'data' => $list);
            }
        }
        jsonEcho($res);
    }
    /**
     * 领券中心
     */
    public function action_voucher(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $voucher_model = new voucher_model();
        $today = strtotime('today');
        $results = $voucher_model->query("SELECT * FROM {$voucher_model->table_name} WHERE end >= {$today}");
        $goods_model = new goods_model();
        $in = '';
        if(!empty($results)){
            foreach($results as $k => $v){
                $results[$k]['start'] = date('Y-m-d', $v['start']);
                $results[$k]['end'] = date('Y-m-d', $v['end']);
                if($v['goods_use'] != 0){
                    $garr = explode(',', $v['goods_use']);
                    if(!empty($garr)){
                        foreach($garr as $g){
                            $ginfo = $goods_model->find(array('goods_id' => $g));
                            $results[$k]['goods_info'][] = $ginfo;
                        }
                    }
                }else{
                    $results[$k]['goods_info'][] = [];
                }
                $in .= $v['id'] . ',';
            }
            $in = substr($in, 0, -1);
            $user_voucher_model = new user_voucher_model();
            $uinfo = $user_voucher_model->query("SELECT vid FROM {$user_voucher_model->table_name} WHERE user_id='{$user_id}' AND vid in($in)");

            $get = array();
            foreach($uinfo as $u){
                $get[] = $u['vid'];
            }
            foreach($results as $kk => $vv){
                if(in_array($vv['id'], $get)){
                    $results[$kk]['isget'] = 1;
                }else{
                    $results[$kk]['isget'] = 0;
                }
            }
        }
        jsonEcho(array('ret' => 0, 'data' => $results));
        //jsonEcho(array('ret' => 0, 'data' => array(array('amount' => 10, 'title' => '好的优惠券', 'full_money' => 12, 'desc' => '一周内有效', 'id' => 1, 'point' => 5, 'start_time' => '2018-01-02', 'end_time' => '2018-04-04'))));
    }

    /**
     * 我的优惠券
     */
    public function action_myvoucher(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $user_voucher_model = new user_voucher_model();
        $uinfo = $user_voucher_model->query("SELECT vid,isused FROM {$user_voucher_model->table_name} WHERE user_id='{$user_id}'");
        $vstr = '';
        foreach($uinfo as $k => $v){
            $vstr .= $v['vid'] . ' ,';
        }
        if($vstr != ''){
            $in = substr($vstr, 0, -1);
            $voucher_model = new voucher_model();
            $today = strtotime('today');
            $results = $user_voucher_model->query("SELECT * FROM {$voucher_model->table_name} WHERE id in($in) AND end>='{$today}'");
            foreach($uinfo as $kk => $vv){
                foreach($results as $rk => $rv){
                    if($vv['vid'] == $rv['id']){
                        $rv['start'] = date('Y-m-d', $rv['start']);
                        $rv['end'] = date('Y-m-d', $rv['end']);
                        $uinfo[$kk]['vinfo'] = $rv;
                    }
                }
            }
        }

        jsonEcho(array('ret' => 0, 'data' => $uinfo));
    }
    /**
     * 领取优惠券
     */
    public function action_add_voucher(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $user_voucher_model = new user_voucher_model();
        $vid = (int)request('vid', 0);
        if($user_voucher_model->add($user_id, $vid)) {
            $voucher_model = new voucher_model();
            $voucher_model->query("UPDATE {$voucher_model->table_name} SET num=num-1 WHERE id='{$vid}'");
            jsonEcho(array('ret' => 0));
        }else {
            jsonEcho(array('ret' => 1, 'err' => '您已领过'));
        }
    }

    /**
     * 删除地址
     */
    public function action_consignee_delete(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $consignee_model = new user_consignee_model();
        $affected = $consignee_model->delete(array('id' => (int)request('id', 0), 'user_id' => $user_id));
        if($affected) {
            jsonEcho(array('ret' => 0));
        } else {
            jsonEcho(array('ret' => 1, 'msg' => '删除失败'));
        }
    }

    /**
     * 更新个人资料
     */
    public function action_update_userdata(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $update = (int)request('update', 0);
        $user_model = new user_model();
        $password = request('password', '', 'post');
        $phone = request('phone', '', 'post');
        $bank = request('bank', '', 'post');
        $bank_name = request('bank_name', '', 'post');
        if(ismobilephone($phone) == 1){
            jsonEcho(array('ret' => 5, 'msg'=>'手机错误'));
        }
        $blen = strlen($bank);
        if($blen < 16 || $blen > 20){
            jsonEcho(array('ret' => 6, 'msg'=>'卡号错误'));
        }
        $bnlen = strlen($bank_name);
        if($bnlen < 2 || $blen > 60){
            jsonEcho(array('ret' => 6, 'msg'=>'银行名称错误'));
        }
        $password = md5e($password);
        if($update == 0){
            $affected = $user_model->update(array('user_id' => $user_id), array('password' => $password, 'mobile' => $phone, 'bank' => $bank, 'bank_name' => $bank_name));
        }else{
            $user = $user_model->find(array('openid' => $openid), null, 'password');
            if($password != $user['password']){
                jsonEcho(array('ret' => 6, 'msg'=>'密码错误'));
            }
            $affected = $user_model->update(array('user_id' => $user_id), array('password' => $password, 'mobile' => $phone, 'bank' => $bank, 'bank_name' => $bank_name));
        }
        if($affected) {
            jsonEcho(array('ret' => 0));
        } else {
            jsonEcho(array('ret' => 1, 'msg' => '已更新'));
        }
    }
    /**
     * 订单详情
     */
    public function action_order_details(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = bigintstr($_POST['order_id']);
        $order_model = new order_model();
        if($order = $order_model->find(array('order_id' => $order_id, 'user_id' => $user_id))){
            $condition = array('order_id' => $order_id);
            $consignee_model = new order_consignee_model();
            $consignee = $consignee_model->find($condition);
            $order['receiver'] = $consignee['receiver'];
            $order['address'] = $consignee['province']. $consignee['city'].$consignee['borough'].$consignee['address'];
            $order['mobile'] = $consignee['mobile'];

            $order_goods_model = new order_goods_model();
            $goods_list = $order_goods_model->get_goods_list($order_id);
            foreach($goods_list as $kk => $g){
                $order['ginfo'][$kk]['goods_id'] = $g['goods_id'];
                $order['ginfo'][$kk]['goods_name'] = $g['goods_name'];
                $order['ginfo'][$kk]['goods_image'] = $g['goods_image'];
                $order['ginfo'][$kk]['now_price'] = $g['goods_price'];
                $order['ginfo'][$kk]['goods_qty'] = $g['goods_qty'];
            }

            $order['progress'] = $order_model->get_user_order_progress($order['order_status'], $order['payment_method']);
            $order['status_map'] = $order_model->status_map;
            $order['order_status'] = $this->_order_status[$order['order_status']];

            if($order['order_status'] == 1)
            {
                if(!$this->countdown = $order_model->is_overdue($order_id, $order['created_date'])) $order['order_status'] = 0;
            } elseif($order['order_status'] == 3){
                $shipping_model = new order_shipping_model();
                if($shipping = $shipping_model->find($condition, 'dateline DESC'))
                {
                    $this->countdown = intval($shipping['dateline'] + $GLOBALS['cfg']['order_delivery_expires'] * 86400 - $_SERVER['REQUEST_TIME']);
                    if(!$this->countdown) $order_model->update($condition, array('order_status' => 4));
                }
            }
            $order['created_date'] = date('Y-m-d H:i:s', $order['created_date']);

            jsonEcho(array('ret' => 0, 'data' => $order));
        }
        jsonEcho(array('ret' => 1, 'msg' => '订单不存在'));
    }
    /**
     * 取消订单
     */
    public function action_orders_cancel(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = bigintstr($_POST['order_id']);
        $order_model = new order_model();
        if($order = $order_model->find(array('order_id' => $order_id, 'user_id' => $user_id))) {
            if($order['order_status'] == 1)
            {
                $order_model->update(array('order_id' => $order_id), array('order_status' => 0));
                $order_goods_model = new order_goods_model();
                $order_goods_model->restocking($order_id);
            }
            jsonEcho(array('ret' => 0));
        }
        jsonEcho(array('ret' => 1, 'msg' => '订单不存在'));
    }
    /**
     * 添加收货地址
     */
    public function action_add_address(){
        /**$_POST['user_id'] = 1;
        $_POST['receiver'] = 'dwew';
        $_POST['tel'] = 13444444444;
        $_POST['sheng'] = 3;
        $_POST['city'] = 1;
        $_POST['quyu'] = 2;
        $_POST['adds'] = 'sdfsdfds';**/

        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $data = array(
            'user_id' => $user_id,
            'receiver' => trim(strip_tags(request('receiver', '', 'post'))),
            //'province' => trim(strip_tags(request('sheng', '', 'post'))),
            //'city' => trim(strip_tags(request('city', '', 'post'))),
            //'borough' => trim(strip_tags(request('quyu', '', 'post'))),
            /**'province' => (int)request('sheng', 0, 'post'),
            'city' => (int)request('city', 0, 'post'),
            'borough' => (int)request('quyu', 0, 'post'),**/
            'locationname' => trim(strip_tags(request('locationname', '', 'post'))),
            'address' => trim(strip_tags(request('adds', '', 'post'))),
            'menpai' => trim(strip_tags(request('menpai', '', 'post'))),
            'mobile' => trim(request('tel', '', 'post')),
        );
        $consignee_model = new user_consignee_model();
        $verifier = $consignee_model->verifier($data);
        if(TRUE === $verifier) {
            if($id = (int)request('id', 0)) {
                $consignee_model->update(array('id' => $id, 'user_id' => $user_id), $data);
                $data['id'] = $id;
            } else {
                $data['id'] = $consignee_model->create($data);
            }
            $res = array('ret' => '0', 'data' => $data);
        } else {
            $res = array('ret' => '1', 'err' => $verifier[0]);
        }
        jsonEcho($res);
    }
    /**
     * 收货地址首页
     */
    public function action_address_index(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];
        $consignee_model = new user_consignee_model();
        $consignee_list = $consignee_model->get_user_consignee_list($user_id);
        jsonEcho(array('status' => 0,'data' => $consignee_list));
    }
    /**
     * 设置默认收货地址
     */
    public function action_set_default(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $addr_id = (int)request('addr_id', 0);
        if (!$user_id || !$addr_id) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $consignee_model = new user_consignee_model();
        $consignee_model->update(array('user_id' => $user_id, 'is_default' => 1), array('is_default' => 0));
        $affected = $consignee_model->update(array('id' => $addr_id, 'user_id' => $user_id), array('is_default' => 1));
        if($affected){
            jsonEcho(array('status' => 0));
        }
        jsonEcho(array('status' => 10,'err'=>'设置默认地址失败'));
    }
    /**
     * 获取省份
     */
    public function action_get_province(){
        $province = (int)request('province', 0);
        $area = new area();
        if($province == 0){
            jsonEcho(array('status' => 0, 'data' => $area->get_children_wechat(0)));
        }else{
            $city = (int)request('city', 0);
            jsonEcho(array('status' => 0, 'data' => $area->get_children_wechat($province, $city)));
        }
    }
    public function action_get_area_name(){
        $area = new area();
        $province = (int)request('province', 0);
        $city = (int)request('city', 0);
        jsonEcho( array('ret' => 0, 'data' => $area->get_area_name_wechat($province,$city)));
    }
    /**
     * 添加物品到购物车
     */
    public function action_cart_add(){

        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        if (!$openid || !$sessionId) {
            jsonEcho(array('status' => 10,'err'=>'授权失败！'));
        }
        $userinfo = $this->wechat_is_login($openid, $sessionId);
        if($userinfo['ret'] > 0){
            jsonEcho(array('status' => 11,'err'=>'授权失败！'));
        }
        $uinfo = $userinfo['data'];
        if(empty($uinfo) || $sessionId != $uinfo['sessionid']){
            jsonEcho(array('status' => 9,'err'=>'用户非法！'));
        }
        $uid = $uinfo['user_id'];

        $pid = (int)($_REQUEST['pid']);
        $num = (int)($_REQUEST['num']);
        if (!$pid || !$num) {
            jsonEcho(array('status' => 10,'err'=>'参数错误.'));
        }

        //加入购物车
        $check = $this->check_cart($pid);
        if ($check['ret'] != 0) {
            jsonEcho(array('status' => 1,'err'=>$check['err']));
            exit;
        }

        $check_info = $check['data'];
        //判断库存
        if ($check_info['stock_qty'] <= $num) {
            jsonEcho(array('status'=>0,'err'=>'库存不足！'));
        }
        //判断购物车内是否已经存在该商品
        $key = $this->_key_user_cart . $uid;
        $vcache = vcache::instance();
        $force = isset($_POST['force']) ? 1 : 0;
        $cart_info = $vcache->get($key);
        if (!empty($cart_info) && isset($cart_info[$pid])) {
            if($force){
                $cart_info[$pid]['num'] = $num;
            }else{
                $cart_info[$pid]['num'] = $cart_info[$pid]['num'] + $num;
            }
            $ret = $vcache->set($key, $cart_info, $this->_cache_year);
        }else{
            $cart_info[$pid] = array('goods_id' => $pid,'goods_name' => $check_info['goods_name'], 'goods_image' => $check_info['goods_image'], 'num' => $num, 'addtime' => time(), 'now_price' => $check_info['now_price'], 'original_price' => $check_info['original_price']);
            $ret = $vcache->set($key, $cart_info, $this->_cache_year);
        }

        if($ret){
            jsonEcho(array('status' => 0,'data' => array_values($cart_info))); //该商品已成功加入您的购物车
        }else{
            jsonEcho(array('status' => 1,'err'=>'加入失败.'));
        }
    }
    //购物车添加。删除检测公共方法
    public function check_cart($pid){
        //检查产品是否存在或删除
        $goods_model = new goods_model();
        $check_info = $goods_model->find(array('goods_id' => $pid,'status' => 1));
        if (!$check_info) {
            return array('ret'=> 1,'err'=>'商品不存在或已下架.');
        }
        return array('ret'=>0, 'data' => $check_info);
    }
    public function action_getsessionkey(){
        $appid = $this->_weixin['appid'];
        $secret = $this->_weixin['secret'];

        $code = trim($_POST['code']);
        if (!$code) {
            jsonEcho(array('status'=>1,'err'=>'非法操作a！'));
        }

        if (!$appid || !$secret) {
            jsonEcho(array('status'=>2,'err'=>'非法操作b！'.__LINE__));
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
		if(curl_errno($ch)){
			file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/a.txt', var_export(curl_error($ch), true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
		}
        curl_close($ch);
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/a.txt', var_export($get_token_url, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        echo $res;
    }

    public function action_authlogin(){
        $appid = $this->_weixin['appid'];
        $secret = $this->_weixin['secret'];

        $code = trim($_POST['code']);
        if (!$code) {
            jsonEcho(array('ret'=>1,'err'=>'非法操作a！'));
        }

        if (!$appid || !$secret) {
            jsonEcho(array('ret'=>2,'err'=>'非法操作b！'.__LINE__));
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $res_arr = json_decode($res, true);

        $openid = $res_arr['openid'];
        $sessionId = $res_arr['session_key'];
        if ($openid == 'undefined' || $sessionId == 'undefined') {
            jsonEcho(array('ret'=>10,'err'=>'授权失败！'.__LINE__));
        }

        $con = array();
        $con['openid'] = $openid;
        $key = $this->_key_user . $openid;
        $vcache = vcache::instance();
        //$uinfo = $vcache->get($key);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] == 0){
            jsonEcho($uinfo);
            //jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }

        $user_mode = new user_model();
        $uinfo = $user_mode->find($con,'','user_id,invite,username,openid,mobile,avatar,status,sex,vip,bank,bank_name,reg_time');


        if(empty($uinfo)){
            //未注册
            $data = array();
            $data['username'] = filterEmoji($_POST['nickName']);
            $data['avatar'] = $_POST['headUrl'];
            $data['sex'] = $_POST['gender'];
            $data['openid'] = $openid;
            $data['password'] = '';
            $data['reg_time'] = time();
            $res = $user_mode->create($data);
            if ($res) {
                $user_account = new user_account_model();
                $user_account->create(['user_id' => $res,'balance' => 0.00, 'today' => 0.00, 'cashed' => 0.00]);

                $return['user_id'] = $cachedata['user_id'] = $res;
                $return['nickName'] = $cachedata['nickName'] = $data['username'];
                $return['headUrl'] = $cachedata['headUrl'] = $data['avatar'];
                $return['invite'] = $cachedata['invite'] = $uinfo['invite'];
                $return['phone'] = $cachedata['phone'] = $uinfo['mobile'];
                $return['vip'] = $cachedata['vip'] = $uinfo['vip'];
                $return['bank'] = $cachedata['bank'] = $uinfo['bank'];
                $return['bank_name'] = $cachedata['bank_name'] = $uinfo['bank_name'];
                $cachedata['sessionid'] = $return['sessionid'] = $sessionId;
                $cachedata['openid'] = $return['openid'] = $openid;

                $vcache->set($key, $cachedata, $this->_cache_year);
                jsonEcho(array('ret' => 0,'data' => $return));
            }else{
                jsonEcho(array('ret'=> 7,'err'=>'网络错误！'.__LINE__));
            }
        }
        //已注册
        $return['user_id'] = $cachedata['user_id'] = $uinfo['user_id'];
        $return['nickName'] = $cachedata['nickName'] = trim($_POST['nickName']);
        $return['headUrl'] = $cachedata['headUrl'] = trim($_POST['headUrl']);
        $return['invite'] = $cachedata['invite'] = $uinfo['invite'];
        $return['phone'] = $cachedata['phone'] = $uinfo['mobile'];
        $return['vip'] = $cachedata['vip'] = $uinfo['vip'];
        $return['bank'] = $cachedata['bank'] = $uinfo['bank'];
        $return['bank_name'] = $cachedata['bank_name'] = $uinfo['bank_name'];
        $cachedata['sessionid'] = $return['sessionid'] = $sessionId;
        $cachedata['openid'] = $return['openid'] = $openid;

        $vcache->set($key, $cachedata, $this->_cache_year);

        jsonEcho(array('ret'=>0, 'data'=> $return));
    }

    public function action_test_send(){
        $openid = 'o2S1c5X8AxIqgQo3Ita5s4w5_VP4';
        //$tid = 'G4yXUeqZCCeJQUZZlN3eEqzH5dGDLMREFKEKdB5YPpk';
        $prepay_id = 'wx10111855914866585b25da7c4197487839';
        $data = [
            'keyword1.DATA' => array('value' => 111, 'color' => '#f00'),
            'keyword2.DATA' => array('value' => 222, 'color' => '#f00'),
            'keyword3.DATA' => array('value' => 333, 'color' => '#f00'),
            'keyword4.DATA' => array('value' => 444, 'color' => '#f00'),
            'keyword5.DATA' => array('value' => date('Y-m-d H:i:s'), 'color' => '#f00'),
            'keyword6.DATA' => array('value' => 555, 'color' => '#f00'),
            'keyword7.DATA' => array('value' => date('Y-m-d H:i:s'), 'color' => '#f00'),
            'keyword8.DATA' => array('value' => date('Y-m-d H:i:s'), 'color' => '#f00'),
        ];
        $ret = $this->sendTemplate($openid,$this->_wx_template, $prepay_id, $data);
    }

    //发送模板消息
    public function sendTemplate($touser, $tid, $prepay_id, $page, $arr){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $this->get_acess_token();
        $data = array(
            'touser' => $touser,
            'template_id' => $tid,
            'page' => $page,
            "form_id" => $prepay_id,
            'data' => $arr
        );
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        $data = $this->http_request($url, $json);

        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $file = $path . "wechat_mon_".date("Yn").".txt";
        file_put_contents($file, var_export($data, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        return $data;
    }

    //获取access token
    public function get_acess_token($update=0){
        $key = 'access_token';
        if($update == 0){
            if($token = $this->memcache_get($key)){
                if(is_string($token)){
                    return $token;
                }
            }
        }

        $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_weixin['appid']}&secret={$this->_weixin['secret']}";

        $token = $this->http_request($url);
        if(isset($token['access_token'])){
            $this->memecache_set($key, $token['access_token'], 7000);
            return $token['access_token'];
        }else{
            $this->memecache_delete($key);
        }

    }
    //curl request
    public function http_request($url, $data=array()){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);#以文件流形式返回
        if($data){
            curl_setopt($ch, CURLOPT_POST, 1); #post方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        $ret = json_decode($output, true);
        if(is_array($ret)){
            $arr = $ret;
        }else{
            $arr = $output;
        }
        //释放curl句柄
        curl_close($ch);
        return $arr;
    }

    public function memecache_set($key, $value, $time=600){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->expire($key, $time);
        $redis->set($key,$value);
    }

    public function memcache_get($key){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis->get($key);
    }
    public function memecache_delete($key){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis->delete($key);
    }
    
    public function action_404(){
        exit(1);
    }
    /**
     * 获取地址
     */
    public function action_get_addr(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        //获取收货地址
        $consignee_model = new user_consignee_model();
        $arr['consignee_list'] = $consignee_model->get_user_consignee_list($user_id);
        if ($arr['consignee_list'] == null) {
            $arr['addemt'] = 0;
        }else{
            foreach($arr['consignee_list'] as $v){
                if($v['is_default']){
                    $arr['addemt'] = 0;
                    $arr['consignee_list'] = $v;
                    break;
                }else{
                    $arr['addemt'] = 1;
                }
            }
        }

        /**$free_model = new free_model();
        $month = strtotime(date('Y-m'));
        $free_info = $free_model->find(['user_id' => $user_id]);
        $arr['free'] = 0;
        if(empty($free_info)){
            $arr['free'] = 1;
        }**/




        jsonEcho(array('status' => 0,'data' => $arr));
    }
    /**
     * 保存免费领取的商品
     */
    public function action_save_free(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $goods_id = (int)request('goods_id', 0);
        if(!$goods_id){
            jsonEcho(array('ret' => 5, 'msg'=>'商品部存在'));
        }
        $addr = (int)request('addemt', 0);
        $user_consignee_model = new user_consignee_model();
        $user_consignee_info = $user_consignee_model->find(['id' => $addr, 'user_id' => $user_id]);
        if(empty($user_consignee_info)){
            jsonEcho(array('ret' => 11, 'msg'=>'地址不存在'));
        }

        //判断是否是vip商品
        $vip = (int)request('vip', 0);
        if($vip == 0){
            jsonEcho(array('ret' => 4, 'msg'=>'你不是VIP'));
        }
        if($vip != $uinfo['data']['vip']){
            jsonEcho(array('ret' => 1, 'msg'=>'VIP不匹配'));
        }
        $goods_model = new goods_model();
        $goods_info = $goods_model->find(['goods_id' => $goods_id]);
        if($vip == 1){
            if($goods_info['king'] != 1){
                jsonEcho(array('ret' => 3, 'msg'=>'VIP资格不对'));
            }
        }
        if($vip == 2){
            if($goods_info['zun'] != 1){
                jsonEcho(array('ret' => 3, 'msg'=>'VIP资格不对'));
            }
        }
        //判断是否是VIP且还没领过
        $free_model = new free_model();
        $month = strtotime(date('Y-m'));
        $free_info = $free_model->find(['user_id' => $user_id, 'vip' => $uinfo['data']['vip']]);//判断是否是首次领取
        $time = time();
        if(empty($free_info)){
            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}free (`user_id`, `vip`, `goods_id`, `address`, `status`,`month`,`created_time`,`pay_time`)
                     VALUES ('{$user_id}', '{$vip}', '{$goods_id}', '{$addr}','0', '{$month}','{$time}','{$time}');
                    ";
            $ret = $free_model->execute($sql);
            if($ret){
                jsonEcho(array('ret' => 0));
            }
        }
        $free_info = $free_model->find(['user_id' => $user_id, 'month' => $month]);//非首次领取,需要付邮费，状态为1
        if(empty($free_info)){
            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}free (`user_id`, `vip`, `goods_id`, `address`, `status`,`month`,`created_time`,`pay_time`)
                     VALUES ('{$user_id}', '{$vip}', '{$goods_id}', '{$addr}','1', '{$month}','{$time}','{$time}');
                    ";
            $ret = $free_model->execute($sql);
            if($ret){
                jsonEcho(array('ret' => 1));
            }
        }
        if($free_info['status'] == 1){
            jsonEcho(array('ret' => 1, 'data' => ['price' => $this->_postage_price, 'id' => $free_info['id']]));
        }

        jsonEcho(array('ret' => 2));
    }
    public function action_wxpay_postage(){
        /**$_POST['user_id'] = 1;
        $_POST['order_id'] = 139600005641757;**/
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $order_id = trim($_POST['order_id']);
        if(!$order_id){
            jsonEcho(array('status' => 3,'err'=>'参数异常！'));
        }
        $free_model = new free_model();
        $order_info = $free_model->find(array('id' => $order_id));
        if (!$order_info) {
            jsonEcho(array('status' => 2,'err'=>'无找到支付订单！'));
        }

        if ($order_info['status'] != 1) {
            jsonEcho(array('status' => 1,'err'=>'订单状态异常！'));
        }

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        $order_model = new order_model();
        $orderid = $order_model->create_order_id();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("商品购买_". $order_info['id']);
        $input->SetAttach($order_info['id']);
        $input->SetOut_trade_no($orderid);
        $input->SetTotal_fee(floatval($this->_postage_price)*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
        $input->SetGoods_tag("支付邮费_" . $order_info['id']);
        $input->SetNotify_url($this->_weixin['postage_notify_url']);//'https://t.kuajiewl.com/wapi/wxpay_notify.html'
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($order, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $arr = array();
        $arr['appId'] = $order['appid'];
        $arr['nonceStr'] = $order['nonce_str'];
        $arr['package'] = "prepay_id=".$order['prepay_id'];
        $arr['signType'] = "MD5";
        $arr['timeStamp'] = (string)time();
        $str = $this->ToUrlParams($arr);
        $jmstr = $str."&key=".\WxPayConfig::KEY;
        $arr['paySign'] = strtoupper(MD5($jmstr));
        $this->memecache_set('prepay_id' . $openid, $order['prepay_id']);
        jsonEcho(array('status' => 0, 'data'=>$arr));
    }
    public function action_wxpay_notify_postage(){
        /*$notify = new \PayNotifyCallBack();
        $notify->Handle(false);*/

        $res_xml = file_get_contents("php://input");
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res_xml, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);

        //$ret = json_decode('{"appid":"wxeefd45e32d9364dc","attach":"4","bank_type":"GDB_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1482407062","nonce_str":"ntveeopnra1rcas5vhyvfccbfrwvvhcq","openid":"o2S1c5fM8Eb7Y8Z4udbvB4HLfym4","out_trade_no":"325399002283136","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DDF07CFB35EDBF01215416EDB719C369","time_end":"20180810135936","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000184201808103231496628"}', true);
        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret);
        $file = $path . "wechat_mon_".date("Yn").".txt";
        file_put_contents($file,$content . __LINE__, FILE_APPEND | LOCK_EX);

        //$ret = json_decode('{"appid":"wxeefd45e32d9364dc","attach":"1","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1482407062","nonce_str":"dc1vi8ksynsoz28k57yktu17kwa9i4b8","openid":"o2S1c5X8AxIqgQo3Ita5s4w5_VP4","out_trade_no":"304450004808015","result_code":"SUCCESS","return_code":"SUCCESS","sign":"D9124FD0160789CE1891F920EC24715A","time_end":"20180409162720","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000059201804095207016326"}', true);
        if($ret['result_code'] != 'SUCCESS' || $ret['return_code'] != 'SUCCESS'){
            echo 'fail';
            exit;
        }
        $wechat_arr = array(
            'id' => $ret['attach'],
            'out_trade_no' => $ret['out_trade_no'],
            'bank_type' => $ret['bank_type'],
            'cash_fee' => $ret['cash_fee'],
            'total_fee' => $ret['total_fee'],
            'fee_type' => $ret['fee_type'],
            'is_subscribe' => $ret['is_subscribe'],
            'openid' => $ret['openid'],
            'transaction_id' => $ret['transaction_id'],
            'time_end' => $ret['time_end']
        );
        //$wechat_mode = new wechatpay_model();
        //$wechat_mode->create($wechat_arr);
        $data = array();
        $data['id'] = $ret['attach'];
        $result = $this->orderhandle_postage($data);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            $condition = array('id' => $ret['out_trade_no']);

            $free_model = new free_model();
            $affected = $free_model->update(array('id' => $ret['attach']), array('status' => 2, 'pay_time' => time()));
            if($affected) {
                file_put_contents($file, var_export('更新用户邮费成功', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            } else {
                file_put_contents($file, var_export('更新用户邮费失败', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            }

            //发送模板消息
            //$tid = 'hDuWaRojW0-5vKgDMenMjmGv-0SmqDTioJln9PNUEXY';
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $this->_postage_price . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s')),
                'keyword4' => array('value' => '支付邮费'),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/user';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($file, $contents . __LINE__, FILE_APPEND | LOCK_EX);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle_postage($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $free_model = new free_model();
        $condition = array('id' => $data['id'], 'status' => 1);
        $order_info = $free_model->find($condition);

        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $free_model->update($condition, array('status' => 2, 'pay_time' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {

            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }

    //获取产品二维码
    public function action_get_qrcode(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        $id = (int)request('id', 0);
        if(!$id){
            jsonEcho(array('ret' => 6, 'msg'=>'参数错误'));
        }
        if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/upload/qrcode/' . $user_id . '_' . $id . '.png')){
            jsonEcho(array('ret' => 0,'data' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'] . '/upload/qrcode/' . $user_id . '_' . $id . '.png'));
        }

        $token = $this->get_acess_token();
        $request = $this->http_request('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token, json_encode(['page' => 'pages/product/detail', 'scene' => 'id=' . $id . '&invite=' . $user_id,'width' => 280]));
        if(isset($request['errcode'])){
            if($request['errcode'] == '42001'){
                $token = $this->get_acess_token(1);
                $request = $this->http_request('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token, json_encode(['page' => 'pages/product/detail','scene' => 'id=' .$id . '&invite=' . $user_id,'width' => 280]));
                //echo $request;
            }
        }else{
            //echo $request;
        }
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/upload/qrcode/' . $user_id . '_' . $id . '.png', $request);
        jsonEcho(array('ret' => 0,'data' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'] . '/upload/qrcode/' . $user_id . '_' . $id . '.png'));
    }
    //获取个人二维码
    public function action_get_vip_qrcode(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];


        if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/upload/user_qrcode/' . $user_id . '.png')){
            jsonEcho(array('ret' => 0,'data' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'] . '/upload/user_qrcode/' . $user_id . '.png'));
        }

        $token = $this->get_acess_token();
        $request = $this->http_request('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token, json_encode(['page' => 'pages/index/index', 'scene' => 'invite=' . $user_id,'width' => 280]));
        if(isset($request['errcode'])){
            if($request['errcode'] == '42001'){
                $token = $this->get_acess_token(1);
                $request = $this->http_request('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token, json_encode(['page' => 'pages/index/index','scene' => 'invite=' . $user_id,'width' => 280]));
                //echo $request;
            }
        }else{
            //echo $request;
        }
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/upload/user_qrcode/' . $user_id . '.png', $request);
        jsonEcho(array('ret' => 0,'data' => $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'] . '/upload/user_qrcode/' . $user_id . '.png'));
    }
    //提现列表
    public function action_cash_list(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        if(!isset($_POST['page'])){
            $page = 0;
        }else{
            $page = (int)request('page', 0);
        }
        $start = $page * 20;
        $fields = 'money,dateline';
        $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_cash_log WHERE user_id='{$user_id}' ORDER BY id DESC limit $start, 20";
        //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $user_cash_log_model = new user_cash_log_model();
        $data = $user_cash_log_model->query($sql);
        //$status_texy = ['失败','成功','申请中'];
        foreach($data as $k => $v){
            $data[$k]['dateline'] = date('Y-m-d H:i:s', $data[$k]['dateline']);
        }
        jsonEcho(array('ret' => 0, 'data' => $data));
    }
    //奖励列表
    public function action_prize_list(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        if(!isset($_POST['page'])){
            $page = 0;
        }else{
            $page = (int)request('page', 0);
        }
        $start = $page * 20;
        $fields = 'prize,balance,num,type,dateline';
        $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log WHERE user_id='{$user_id}' ORDER BY id DESC limit $start, 20";
        //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $user_account_log = new user_account_log_model();
        $data = $user_account_log->query($sql);
        foreach($data as $k => $v){
            $data[$k]['prize'] = $this->_weixin['prize'][$v['prize']];
            $data[$k]['type'] = $this->_weixin['income_type'][$v['type']];
            $data[$k]['dateline'] = date('Y-m-d', $data[$k]['dateline']);
        }
        jsonEcho(array('ret' => 0, 'data' => $data));
    }
    //返佣列表
    public function action_rake_back_list(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        if(!isset($_POST['page'])){
            $page = 0;
        }else{
            $page = (int)request('page', 0);
        }
        $start = $page * 20;
        $fields = 'goods_name,money,num,rake_back,dateline';
        $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_rake_back WHERE user_id='{$user_id}' ORDER BY id DESC limit $start, 20";
        //file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $user_rake_back_model = new user_rake_back_model();
        $data = $user_rake_back_model->query($sql);
        foreach($data as $k => $v){
            $data[$k]['dateline'] = date('Y-m-d', $data[$k]['dateline']);
        }
        jsonEcho(array('ret' => 0, 'data' => $data));
    }
    /**
     *
    1️：购买99元成为金卡VIP会员，每天分享产品生成二维码海报发朋友圈，立得佣金补贴奖励。
    2️：分享好友成为金卡VIP会员可得奖励，一级奖励9元，二级奖励9元
    【管理奖可领一级二级各9天】一级金卡VIP会员发朋友圈你可以每天得3元/件《每天可以分享2件》
    二级金卡VIP会员发朋友圈你可以每天得2元/件《每天可以分享2件》
    3：新老会员皆可支付999元可以升级成为尊贵VIP会员！无需先升级金卡VIP！
    4：每天可以分享生成2件产品二维码到朋友圈，每完成一件产品生成二维码海报发到朋友圈可以获得10元奖励！每天2件产品奖励20元
    5：尊贵VIP直推尊贵VIP获得1级90元奖励，2级90元奖励！
    【管理奖可领一级二级各14天】每天可以获得1级尊贵VIP分享产品二维码每件10元奖励！《每天可以分享2件》2级尊贵VIP分享每件5元奖励！《每天可以分享2件》
    6：尊贵VIP推荐金卡VIP可以获得1级9元奖励，2级9元奖励！
    【管理奖可领一级二级各9天】每天可以获得1级金卡VIP分享每件3元奖励！《每天可以分享2件》2级金卡VIP分享每件2元奖励！《每天可以分享2件》
    7：尊贵VIP直接推荐20个尊贵VIP成为市场总监，可以获得辖区内每新增一个尊贵VIP奖励20元！每新增一个金卡VIP奖励2元！
    8：市场总监可领取伞下育成市场总监每天管理奖收入的10%
    9：金卡VIP会员推荐尊贵VIP会员可以获得1级9元奖励，2级9元奖励！
    【管理奖可领一级二级各9天】每天可以领取1级分享每件3元奖励《每天可以分享2件》，2级分享每件2元奖励！《每天可以分享2件》
     */
    //分享奖励
    public function action_get_share_prize(){
        $id = (int)request('id', 0);
        if(!$id){
            jsonEcho(array('ret' => 1, 'msg'=>'商品部存在'));
        }

        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];
        $invite = $uinfo['data']['invite'];
        $vip = $uinfo['data']['vip'];

        //根据用户的VIP属性决定
        //$vip = $uinfo['data']['vip'];
        if(!$vip){
            jsonEcho(array('ret' => 2, 'msg'=>'VIP才享有返佣'));
        }
        $condition = array('goods_id' => $id);
        $goods_model = new goods_model();
        $today = strtotime('today');
        $time = time();
        $income_type = 1;
        $invite_income_type = 2;

        $setting_model = new setting_model();
        $rs = $setting_model->get_config();

        $vip_settings = json_decode($rs['vip_settings'], true);
        if($vip == 1){//['金卡VIP直推奖','金卡VIP分享奖','金卡VIP管理奖','尊贵VIP直推奖','尊贵VIP直推奖','尊贵VIP管理奖']
            $fields = 'king';
            $goods = $goods_model->find($condition, null, $fields);
            if($goods['king'] != 1){ //分享非金牌VIP产品
                jsonEcho(array('ret' => 0));
            }
            $my_money = $vip_settings['king_rake_back'];
            //$invite_money = $vip_settings['king_service_back'];
            //$invite_money2 = $vip_settings['king_service_back2'];
            $self_prize = 1;
        }
        if($vip == 2){
            $fields = 'zun';
            $goods = $goods_model->find($condition, null, $fields);
            if($goods['zun'] != 1){ //分享非至尊VIP产品
                jsonEcho(array('ret' => 0,'data' => '222'));
            }
            $my_money = $vip_settings['zun_rake_back'];
            //$invite_money = $vip_settings['zun_service_back'];
            //$invite_money2 = $vip_settings['zun_service_back2'];
            $self_prize = 4;
        }
        $user_share = new user_share_receive_model();
        $share = $user_share->find_count(['user_id' => $user_id, 'day' => $today]);

        //判断每天可分享的产品次数，判断对应VIP能领取的天数
        $first = date('Y-m-01');
        $start = strtotime(date('Y-m-01',strtotime(date('Y-m-d'))));
        $end = strtotime(date('Y-m-d 23:59:59', strtotime("$first +1 month -1 day")));
        $sql = "SELECT distinct(day) FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_share_receive WHERE user_id='{$user_id}' AND day>='{$start}' AND day<='{$end}';";
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        $count = $user_share->execute($sql);
        $daycount = count($count);

        if($vip == 1){
            //当天领取次数
            if($share >= $vip_settings['king_time']){
                jsonEcho(array('ret' => 0, 'data' => '3'));
            }
            //判断能领多少天
            if($daycount >= $vip_settings['king_day']){
                jsonEcho(array('ret' => 0, 'data' => '4'));
            }
        }
        if($vip == 2){
            //当天领取次数
            if($share >= $vip_settings['zun_time']){
                jsonEcho(array('ret' => 0, 'data' => '5'));
            }
            //判断能领多少天
            if($daycount >= $vip_settings['zun_day']){
                jsonEcho(array('ret' => 0, 'data' => '6'));
            }
        }
        $user_model = new user_model();
        $user_acctount = new user_account_model();
        $acctount_log = new user_account_log_model();
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($share, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if($share == 0){ //今天还没分享过直接插入数据+金币
            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_share_receive (`user_id`,`goods_id`, `money`, `day`, `dateline`)
                     VALUES ('{$user_id}', '{$id}', '{$my_money}', '{$today}', '{$time}');";
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            $ret = $user_share->execute($sql);

            if($ret){
                //加入今日收入，收入日志
                $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$my_money,today=today+$my_money WHERE user_id='{$user_id}';";

                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                $ret = $user_acctount->execute($sql);
                //插入日志
                if($ret){
                    $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_id}', '{$self_prize}', '{$my_money}','1', '1', '{$time}');";
                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $acctount_log->execute($sql);


                    //给1级加返佣
                    if($invite > 0){
                        $invite_one = $user_model->find(['user_id' => $invite], null, 'invite,vip');
                        if($invite_one['vip'] > 0){
                            $invite_prize = 2;
                            $invite_money = $vip_settings['king_service_back'];
                            if($vip == 2 && $invite_one['vip'] == 2){
                                $invite_money = $vip_settings['zun_service_back'];
                                $invite_prize = 5;
                            }
                            $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$invite_money,today=today+$invite_money WHERE user_id='{$invite}';";
                            $user_acctount->execute($sql);
                            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$invite}', '{$invite_prize}', '{$invite_money}','1', '{$invite_income_type}', '{$time}');";
                            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                            $acctount_log->execute($sql);

                            //给2级加返佣
                            if($invite_one['invite'] > 0){
                                //$sql = "SELECT invite FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$invite}';";
                               // $invite_data = $user_model->execute($sql);

                                $invite_two = $user_model->find(['user_id' => $invite_one['invite']], null, 'invite,vip');
                                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($user_model->dump_sql(), true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($invite_two, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                if($invite_two['vip'] > 0){
                                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export(6666, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                    $invite_prize = 2;
                                    $invite_money2 = $vip_settings['king_service_back2'];
                                    if($vip == 2 && $invite_two['vip'] == 2){
                                        $invite_money2 = $vip_settings['zun_service_back2'];
                                        $invite_prize = 5;
                                    }

                                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$invite_money2,today=today+$invite_money2 WHERE user_id='{$invite_one['invite']}';";

                                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


                                    $user_acctount->execute($sql);
                                    $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$invite_one['invite']}', '{$invite_prize}', '{$invite_money2}','1', '{$invite_income_type}', '{$time}');";
                                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                                    $acctount_log->execute($sql);
                                }
                            }

                        }


                    }


                    jsonEcho(array('ret' => 0, 'data'=>'加' . $my_money . '金币'));
                }

            }
        }
        if($share < 2){//分享次数<2且当前商品未分享，插入数据+金币
            $user_share = new user_share_receive_model();
            $share = $user_share->find_count(['user_id' => $user_id, 'goods_id' => $id, 'day' => $today]);
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($share, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            if($share == 0){
                $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_share_receive (`user_id`,`goods_id`, `money`, `day`, `dateline`)
                     VALUES ('{$user_id}', '{$id}', '{$my_money}', '{$today}', '{$time}');";
                $ret = $user_share->execute($sql);
                if($ret){
                    //加入今日收入，收入日志
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$my_money,today=today+$my_money WHERE user_id='{$user_id}';";
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_id}', '{$self_prize}', '{$my_money}','1', '1', '{$time}');";
                        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                        $acctount_log->execute($sql);


                        if($invite > 0){
                            $invite_one = $user_model->find(['user_id' => $invite], null, 'invite,vip');
                            if($invite_one['vip'] > 0) {
                                $invite_prize = 2;
                                $invite_money = $vip_settings['king_service_back'];
                                if ($vip == 2 && $invite_one['vip'] == 2) {
                                    $invite_money = $vip_settings['zun_service_back'];
                                    $invite_prize = 5;
                                }
                                //给1级加返佣
                                $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$invite_money,today=today+$invite_money WHERE user_id='{$invite}';";
                                $user_acctount->execute($sql);
                                $acctount_log = new user_account_log_model();
                                $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$invite}', '{$invite_prize}', '{$invite_money}','1', '{$invite_income_type}', '{$time}');";
                                $acctount_log->execute($sql);

                                //给2级加返佣
                                if($invite_one['invite'] > 0){
                                    //$sql = "SELECT invite FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$invite}';";
                                    //$invite_data = $user_model->execute($sql);
                                    $invite_two = $user_model->find(['user_id' => $invite_one['invite']], null, 'invite,vip');
                                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($user_model->dump_sql(), true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($invite_two, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                    if($invite_two['vip'] > 0){
                                        $invite_prize = 2;
                                        $invite_money2 = $vip_settings['king_service_back2'];
                                        if($vip == 2 &&  $invite_two['vip'] == 2){
                                            $invite_money2 = $vip_settings['zun_service_back2'];
                                            $invite_prize = 5;
                                        }

                                        $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$invite_money2,today=today+$invite_money2 WHERE user_id='{$invite_one['invite']}';";
                                        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                        $user_acctount->execute($sql);
                                        $acctount_log = new user_account_log_model();
                                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$invite_one['invite']}', '{$invite_prize}', '{$invite_money2}','1', '{$invite_income_type}', '{$time}');";

                                        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                                        $acctount_log->execute($sql);
                                    }
                                }
                            }

                        }

                        jsonEcho(array('ret' => 0, 'data'=>'加' . $my_money . '金币'));
                    }
                }
            }
        }
        jsonEcho(array('ret' => 22));
    }

    //转钱到用户领钱
    public function action_transfers(){
        $post_cash = (int)request('num', 0);
        if(!in_array($post_cash, [50, 100, 500, 1000])){
            jsonEcho(array('ret' => 13, 'msg'=>'提现金额非法'));
        }

        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        //判断本地账户
        $today = strtotime('today');
        $user_cash_log = new user_cash_log_model();
        $cash_data = $user_cash_log->find_count(['user_id' => $user_id, 'day' => $today]);//今天是否已提现
        if($cash_data > 0){
            jsonEcho(array('ret' => 15, 'msg'=>'每天限提一次'));
        }
        //今天没提现看看账户金额是否足够
        $user_account = new user_account_model();
        $money_data = $user_account->find(['user_id' => $user_id], null, 'balance,today,cashed');
        if($money_data['balance'] < $post_cash){
            jsonEcho(array('ret' => 16, 'msg'=>'余额不足'));
        }
        //减去账户金额
        /**$sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance-$post_cash WHERE user_id='{$user_id}' AND balance>=$post_cash LIMIT 1;";
        $ret = $user_account->execute($sql);
        if(!$ret){
            jsonEcho(array('ret' => 17, 'msg'=>'余额不足'));
        }**/

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        $time = time();
        $cash_log = new user_cash_log_model();
        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_cash_log (`user_id`,`money`, `status`, `day`,`dateline`)
                     VALUES ('{$user_id}', '{$post_cash}', '2', '{$today}', '{$time}');";
        $cash_log->execute($sql);
        jsonEcho(array('ret' => 0, 'msg'=>'申请成功'));

    }

    public function action_transfers_wx(){
        $post_cash = (int)request('num', 0);
        if(!in_array($post_cash, [50, 100, 500, 1000])){
            jsonEcho(array('ret' => 13, 'msg'=>'提现金额非法'));
        }

        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        //判断本地账户
        $today = strtotime('today');
        $user_cash_log = new user_cash_log_model();
        $cash_data = $user_cash_log->find_count(['user_id' => $user_id, 'day' => $today]);//今天是否已提现
        if($cash_data > 0){
            jsonEcho(array('ret' => 15, 'msg'=>'每天限提一次'));
        }
        //今天没提现看看账户金额是否足够
        $user_account = new user_account_model();
        $money_data = $user_account->find(['user_id' => $user_id], null, 'balance,today,cashed');
        if($money_data['balance'] < $post_cash){
            //jsonEcho(array('ret' => 16, 'msg'=>'余额不足'));
        }
        //减去账户金额
        $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance-$post_cash WHERE user_id='{$user_id}' AND balance>=$post_cash LIMIT 1;";
        $ret = $user_account->execute($sql);
        if(!$ret){
            jsonEcho(array('ret' => 17, 'msg'=>'余额不足'));
        }

        //①、获取用户openid
        require_once $_SERVER['DOCUMENT_ROOT'] . '/protected/lib/WeiXinpay/wxpay.php';
        $tools = new JsApiPay();
        if (!$openid) {
            echo json_encode(array('status' => 4,'err'=>'用户状态异常！'));
            exit();
        }

        $orderid = date('YmdHis') . substr(microtime(), 2, 5);
        //②、统一下单
        $input = new \WxPayPaymentToUser();
        $input->SetPartner_trade_no($orderid);
        $input->SetCheck_name('NO_CHECK');
        $input->SetAmount(50);
        $input->SetDesc('提现');
        $input->SetOpenid($openid);
        $order = \WxPayApi::paymentUser($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        if($order['return_code'] == 'SUCCESS'){
            $time = time();
            if($order['result_code'] == 'SUCCESS'){
                //提现日志
                $cash_log = new user_cash_log_model();
                $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_cash_log (`user_id`,`money`, `status`, `day`,`dateline`)
                     VALUES ('{$user_id}', '{$post_cash}', '1', '{$today}', '{$time}');";
                $cash_log->execute($sql);
                jsonEcho(array('ret' => 0, 'msg'=>'提现成功'));
            }
            if($order['result_code'] == 'FAIL'){
                $cash_log = new user_cash_log_model();
                $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_cash_log (`user_id`,`money`, `status`, `day`,`dateline`)
                     VALUES ('{$user_id}', '{$post_cash}', '0', '{$today}', '{$time}');";
                $cash_log->execute($sql);
                if($order['return_msg'] == 'NO_AUTH'){
                    jsonEcho(array('ret' => 2, 'msg'=>'应用无付款权限'));
                }
                if($order['return_msg'] == 'NOTENOUGH'){
                    jsonEcho(array('ret' => 3, 'msg'=>'应用余额不足'));
                }
                if($order['return_msg'] == 'V2_ACCOUNT_SIMPLE_BAN'){
                    jsonEcho(array('ret' => 4, 'msg'=>'非实名用户'));
                }
            }
        }
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($order, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

    }

    //奖励列表 [废弃]
    public function action_invite_list(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }
        $user_id = $uinfo['data']['user_id'];

        if(!isset($_POST['page'])){
            $page = 0;
        }else{
            $page = (int)request('page', 0);
        }
        $start = $page * 20;

        $level = (int)request('level', 0);
        if(!in_array($level, [1,2])){
            jsonEcho(array('ret' => 2, 'msg'=>'参数错误'));
        }

        $fields = 'user_id,invite,username,mobile,vip,reg_time';
        $user_model = new user_model();
        $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE invite='{$user_id}' limit $start, 20";
        $data = $user_model->query($sql);

        $level2 = '';
        foreach($data as $k => $v){
            if(!$data[$k]['mobile']){
                $data[$k]['mobile'] = '暂无';
            }
            $data[$k]['reg_time'] = date('Y-m-d', $data[$k]['reg_time']);
            if($data[$k]['invite']){
                $level2 .= $data[$k]['user_id'] . ',';
                $data[$k]['invite'] = $uinfo['data']['username'];
            }
            $level1_data[$v['user_id']] = $v;
        }

        if($level == 2){
            $level2 = substr($level2, 0, -1);
            $sql = "SELECT {$fields} FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE invite in({$level2}) limit $start, 20";
            $data = $user_model->query($sql);
            foreach($data as $k => $v){
                if(!$data[$k]['mobile']){
                    $data[$k]['mobile'] = '暂无';
                }
                if(isset($level1_data[$v['invite']])){
                    $data[$k]['invite'] = $level1_data[$v['invite']]['username'];
                }
                $data[$k]['reg_time'] = date('Y-m-d', $data[$k]['reg_time']);
            }
        }
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


        jsonEcho(array('ret' => 0, 'data' => $data));
    }

    //获取设置
    public function action_get_settings(){
        $openid = trim($_POST['openid']);
        $sessionId = trim($_POST['seesionid']);
        $uinfo = $this->wechat_is_login($openid, $sessionId);
        if($uinfo['ret'] > 0){
            jsonEcho(array('ret' => 10, 'msg'=>'授权失败！'));
        }

        $type =trim(request('type', ''));

        $setting_model = new setting_model();
        $rs = $setting_model->get_config();
        $settings = json_decode($rs['vip_settings'], true);
        if(isset($settings[$type])){
            jsonEcho(array('ret' => 0, 'data' => $settings[$type]));
        }
        if($type == 'king'){
            jsonEcho(array('ret' => 0, 'data' => ['desc' => $settings['vip_desc'], 'price' => $settings['king_price']]));
        }elseif($type == 'zun'){
            jsonEcho(array('ret' => 0, 'data' => ['desc' => $settings['zun_desc'], 'price' => $settings['zun_price']]));
        }elseif($type == 'guwen'){
            jsonEcho(array('ret' => 0, 'data' => ['desc' => $settings['guwen_desc'], 'price' => $settings['guwen_price']]));
        }
        jsonEcho(array('ret' => 2, 'msg'=>''));
    }

    //定时任务重置当天收入
    public function action_reset_today_income(){
        $time = time();
        $today = strtotime('today');
        $end = $today + 200;
        if($time > $today && $time < $end){
            $user_acctount = new user_account_model();
            $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET today='0.00';";
            $ret = $user_acctount->execute($sql);

            //删除上个月分享的商品
            /**$start = strtotime(date('Y-m-01',strtotime(date('Y-m-d'))));
            $share_model = new user_share_receive_model();
            $sql = "DELETE FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_share_receive WHERE day<'{$start}'";
            $share_model->query($sql);**/

            if($ret){
                jsonEcho(array('ret' => 0));
            }
        }

        jsonEcho(array('ret' => 1));
    }
}